美文网首页
Laravel 中的异常处理

Laravel 中的异常处理

作者: 伍源辉 | 来源:发表于2017-02-15 10:45 被阅读422次

Laravel 中的所有异常都由类App\Exceptions\Handler集中处理,这个类有两个方法:report 和 render。

report 方法

report 方法用于记录异常并将其发送给外部服务。默认情况下,report 方法只是将异常传递给异常基类并写入日志进行记录,我们可以在 report 中自定义异常日志记录行为。

例如,如果你需要针对不同的异常类型进行不同的记录方式,可使用 PHP 的 instanceof 操作符进行判断:

public function report(Exception $e){
    if ($e instanceof CustomException) {
        // log custom exception
    } elseif ($e instanceof OtherException) {
        // log other exception
    }

    return parent::report($e);
}

dontReport 属性

异常处理器的 $dontReport 属性用于定义不进行记录的异常类型。默认情况下,HttpException 和 ModelNotFoundException 异常不会被记录,我们可以添加其他需要忽略的异常类型到这个数组。

render 方法

render 方法负责将异常转化为 HTTP 响应。默认情况下,异常会传递给 Response 基类生成响应。我们可以 render 方法中进行异常捕获和返回自定义的 HTTP 响应:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function render($request, Exception $e){
    if ($e instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    } elseif ($e instanceof OtherException) {
        return response()->json(['msg'=>'Other Exception'], 401);
    } elseif ($e instanceof NotFoundHttpException) {
        // Your stuff here
    }

    return parent::render($request, $e);
}

相关文章

网友评论

      本文标题:Laravel 中的异常处理

      本文链接:https://www.haomeiwen.com/subject/emtqwttx.html