怎么在Laravel中对错误与异常进行处理?

2021-02-1317:01:52后端程序开发Comments1,254 views字数 1524阅读模式

忽略异常文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

在 $dontReport 中可以定义忽略的异常类名:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

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 方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

几个重要方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

主要介绍这三个方法,report,render 和 unauthenticated 的用法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

report方法
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

report 方法可以用来记录日志,可以根据不同的异常类型(包括自定义异常类型),如 ClientException,ConnectException 定制不同的日志级别和日志内容。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

if ($exception instanceof ABCException) {
 Log::emergency('ABC异常', $context);
} else if ($exception instanceof HeheException) {
 Log::info('Hehe异常', $context);
}

report 方法没有返回值,也不应该在这里中断程序。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

render方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

render 方法可以根据不同的异常类型,返回不同的数据。如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

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);
}

unauthenticated文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

在访问需要登录态的页面时,用户未登录就会进入这个方法进行处理,举个例子说明:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

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,则统一返回格式。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

默认情况下返回前台的登录页,如果是访问后台页面未登录,则跳转到后台登录页。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

看完上述内容,你们掌握怎么在Laravel中对错误与异常进行处理的方法了吗?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/20954.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/20954.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定