我正在尝试显示一个自定义错误页面,如果错误不是“找不到页面”或身份验证问题(例如,尝试访问用户不知道的页面),我希望显示该页面可使用)。我在 Laravel 5.3 的 Handler.php 中使用下面的代码。虽然 404 部分有效,但身份验证部分不起作用(触发此错误只是返回 500 页面)。我错过了什么?
public function render($request, Exception $e)
{
if ($e instanceof NotFoundHttpException || $e instanceof AuthorizationException || $e instanceof AuthenticationException) {
return parent::render($request, $e);
}
else {
return response()->view('errors.500', [
'sentryID' => $this->sentryID,
], 500);
}
}
最佳答案
编辑:看起来您想要处理所有全局错误页面。 Laravel 使用 symfony 的异常处理程序来生成错误页面文本和样式。这可以在以下位置找到:
vendor/symfony/debug/ExceptionHandler.php
它在 vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php
中使用为
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
要处理每个错误和异常,您可以将方法 prepareResponse
扩展到 app/Exceptions/Handler.php
并进行适当的更改。
protected function prepareResponse($request, Exception $e)
{
if ($this->isHttpException($e)) {
return $this->toIlluminateResponse($this->renderHttpException($e), $e);
} else {
return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
}
}
您可以在 vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php
结束编辑
您不需要为此搞乱渲染方法。 Laravel 开箱即用地搜索错误 View 并根据错误代码呈现它们(如果可用)。因此,对于 404 和 500,您只需创建以下两个 View 并在其中进行自定义即可。
resources/views/errors/404.blade.php
resources/views/errors/500.blade.php
此 View 获取异常、状态和 header 信息,以便您在需要时显示。他们是这样称呼的
return response()->view("errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
用于身份验证检查。当用户未经身份验证时,Laravel 会调用 app/Exceptions/Handler.php
中的 unauthenticated
方法。默认情况下,此代码会将用户重定向到登录页面或显示 json 响应。您可以在此处进行更改。
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}
关于php - 如何在 Laravel 的 Handler 渲染中捕获授权错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44061154/