Laravel 中如何处理错误和异常?
忽略异常
在$dontReport中,您可以定义忽略的异常类名称:
protected $dontReport = [ \Illuminate\Auth\AuthenticationException::class, \Illuminate\Auth\Access\AuthorizationException::class, \Symfony\Component\HttpKernel\Exception\HttpException::class, \Illuminate\Database\Eloquent\ModelNotFoundException::class, \Illuminate\Validation\ValidationException::class, ];
这些异常将不会通过report方法进行处理。
几种主要的方法
主要介绍Report、render、Unverified这三种方法的使用。
报告方法
报告方法可用于捕获日志。可以根据不同的异常类型(包括自定义异常类型)定制不同的日志级别和日志内容,例如ClientException、ConnectException等。
if ($exception instanceof ABCException) { Log::emergency('ABC异常', $context); } else if ($exception instanceof HeheException) { Log::info('Hehe异常', $context); }
report 方法没有返回值,程序不应在此中断。
render方法
render方法可以根据不同的异常类型返回不同的数据。例如:
if (get_class($exception) == 'Exception' || $exception instanceof NotAllowedException) { return response()->json(['message' => $exception->getMessage()], 400); } elseif ( $exception instanceof ValidationException) { return response()->json(['message' => '校验失败', 'errors'=> $exception->validator->errors()], 400); }
未验证
在访问需要登录的页面时,如果用户没有登录,就会进入该方法进行处理。例如:
protected function unauthenticated($request, AuthenticationException $exception) { if ($request->expectsJson()) { return response()->json(['error' => 'Unauthenticated.'], 401); } //如果是后台页面未认证,跳转到后台登陆页面 $guard = $exception->guards(); if (in_array('admin', $guard)) { return redirect()->guest('/admin/login'); } return redirect()->guest('login'); }
如果返回json,则返回格式统一。
默认返回前端登录页面。如果没有登录访问后台页面,会跳转到后台登录页面。
看完上面的内容,你知道Laravel中如何处理错误和异常了吗?
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。