讨论数量:
如果是要自定义 未认证的异常
, 可以尝试在 App\Exceptions\Handler
中重写 unauthenticated()
/**
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
*
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson() ? response()->json(['code' => 401, 'message' => $exception->getMessage()]) : redirect()->guest($exception->redirectTo() ?? route('login'));
}
应该先需要在App\Providers\AppServiceProvider.php文件内重写一下boot方法,交给 App\Exceptions\Handler 来接管处理。
public function boot()
{
app('api.exception')->register(function (\Exception $exception) {
$request = Request::capture();
return app('App\Exceptions\Handler')->render($request, $exception);
});
}
然后在App\Exceptions\Handler.php文件中render方法中进行异常捕获处理
推荐文章: