laravel 5 渲染 AccessDeniedHttpException

Pra*_*dám 2 exception-handling exception laravel

为什么它没有以给定的方式呈现?除了 AccessDeniedHttpException 之外,其他类型的异常都运行良好

应用程序/异常/Handler.php

use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException as AccessDeniedHttpException;
... 

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
...
            // 403 Forbidden
            if ($exception instanceof AccessDeniedHttpException)
            {
                return response()->json([
                    'code' => 403,
                    'message' => 'This action is unauthorized1.',
                ],403);
            }
            // 401 Unauthorized
            if ($exception instanceof AuthenticationException)
            {
                return response()->json([
                    'code' => 401,
                    'message' => 'Unauthenticated error.',
                ],  401);
            }
Run Code Online (Sandbox Code Playgroud)

401 就像一个魅力,但 403 执行原始渲染。

任何解决方案?

小智 9

尝试将其包含在您的App\Exceptions\Handler.php. 请务必use Illuminate\Auth\Access\AuthorizationException;在您的顶部添加Hander.php

protected $dontReport = [
    \Illuminate\Auth\Access\AuthorizationException::class,
];
Run Code Online (Sandbox Code Playgroud)

显然,AccessDeniedHttpException是 的一个实例AuthorizationException

public function render($request, Exception $exception)
{
    //Useful since some methods cannot be accessed in certain URL extensions
    if ($exception instanceof AuthorizationException) {
        return response()->view('errors.404', [], 404);
    }

    return parent::render($request, $exception);
}
Run Code Online (Sandbox Code Playgroud)