Laravel 异常处理程序未捕获来自表单请求的请求异常

Laravel exception handler not catching request exception from Form request

请求授权将在我的案例中抛出 AccessDeniedException 错误

class IndexRequest extends FormRequest
{
   public function authorize()
   {
       return auth()->user()->can('list-foos');
   }
}

由此,路由绑定在索引函数上

public function index(IndexRequest $request)

在处理程序中 class,

$this->reportable(function (AccessDeniedHttpException $e) {
    return $this->response('unauthorized', 403);
});

但是

"message": "This action is unauthorized.", "exception":"Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException", "file":"/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php", "line": 356,

作为响应被抛出

我试图从 Spatie 文档中捕获异常

https://spatie.be/docs/laravel-permission/v5/advanced-usage/exceptions

发现了。我必须使用 render() 函数而不是 register()

Illuminate\Auth\Access\AuthorizationException

public function render($request, Throwable $exception)
{
    if ($exception instanceof AuthorizationException) {
        return $this->responseUnauthroized('Unauthorized');
    }
}