3 回答

TA貢獻1744條經驗 獲得超4個贊
如果你查看源代碼,Symfony\Component\HttpKernel\Exception\NotFoundHttpException你會發現它擴展了,Symfony\Component\HttpKernel\Exception\HttpException如果你查看類的聲明,你會發現它$statusCode是私有的,但它有一個 getter 方法
class HttpException extends \RuntimeException implements HttpExceptionInterface
{
private $statusCode;
private $headers;
public function __construct(int $statusCode, string $message = null, \Throwable $previous = null, array $headers = [], ?int $code = 0)
{
$this->statusCode = $statusCode;
$this->headers = $headers;
parent::__construct($message, $code, $previous);
}
public function getStatusCode()
{
return $this->statusCode;
}
//...
}
因此,您只需要$exception->getStatusCode()檢索狀態代碼(在您的情況下為 404),盡管您應該進行檢查以確保您的 throwable 實現了,因為情況可能HttpExceptionInterface并不總是如此,因此該方法將不存在,您會得到致命錯誤
if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface) {
$code = $exception->getStatusCode();
}

TA貢獻1796條經驗 獲得超4個贊
我的做法如下,
由于這個問題相對較新,我推測您正在起訴Laravel
版本7或8。根據 的文檔Error Handling
,正確的頁面渲染方法現在如下
public function render($request, Throwable $exception)
{
? ? if ($exception instanceof CustomException) {
? ? return response()->view('errors.custom', [], 500);
? ? }
? ? return parent::render($request, $exception);
}
為了使用自定義錯誤視圖,您必須告訴您拋出的實例Laravel
類型。要覆蓋內部錯誤處理,您需要捕獲作為 HTTP 異常拋出的異常。對于這些版本,正確的類是.?所以,Exception
$exception
Symfony\Component\HttpKernel\Exception\
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
在你的頂部引入處理類app\Exceptions\Handler.php
根據您的場景將默認的 render() 方法修改為如下所示,
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
? ? //
? ? //
public function render($request, Throwable $exception)
{
? ? // return parent::render($request, $exception);
? ? if ($exception instanceof HttpExceptionInterface) {
? ? ? ? if (env('APP_ENV') === 'production' && $exception->getStatusCode() == 404) {
? ? ? ? ? ? return response()->view('errors.404', [], 404);
? ? ? ? }
? ? ? ? if (env('APP_ENV') === 'production' && $exception->getStatusCode() == 500) {
? ? ? ? ? ? return response()->view('errors.500', [], 500);
? ? ? ? }
? ? }
? ? return parent::render($request, $exception);
}
- 3 回答
- 0 關注
- 240 瀏覽
添加回答
舉報