如何在 Laravel 中捕获所有异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48536365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:19:29  来源:igfitidea点击:

How to catch all exceptions in Laravel

laravel

提问by PrStandup

I was wondering if there is a way to catch all the exceptions that are thrown in a laravel app and store them in database ?

我想知道是否有办法捕获 Laravel 应用程序中抛出的所有异常并将它们存储在数据库中?

I have been looking at some packages but coudn't find anything that tells where and how to catch the exceptions.

我一直在查看一些包,但找不到任何说明在哪里以及如何捕获异常的信息。

回答by Milad Teimouri

for catch all errors and log them you need to edit App\Exceptions\Handlerfile like this

要捕获所有错误并记录它们,您需要App\Exceptions\Handler像这样编辑文件

 public function render($request, Exception $exception)
{
    if ($exception){
        // log the error
        return response()->json([
            'status' => $exception->getStatusCode(),
            'error' => $exception->getMessage()
        ]);
   }
    return parent::render($request, $exception);
}

回答by Sapnesh Naik

As stated in the Docs, You need to have to customize the render()method of App\Exceptions\Handler.

正如所陈述的文档,你需要有自定义render()的方法App\Exceptions\Handler

Edit the app/Exceptions/Handler.php:

编辑app/Exceptions/Handler.php

public function render($request, Exception $e)
{
    $error =$e->getMessage();

    //do your stuff with the error message 

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