如何在Laravel中捕获所有异常

PrS*_*dup 2 laravel

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

我一直在寻找一些软件包,但找不到任何可以告诉您如何以及在何处捕获异常的信息。

Sap*_*aik 5

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

编辑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);
}
Run Code Online (Sandbox Code Playgroud)


Mil*_*uri 5

要捕获所有错误并记录它们,您需要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);
}
Run Code Online (Sandbox Code Playgroud)