正如 Digitlimit 之前提到的here https://stackoverflow.com/questions/31935182/laravel-5-override-exception-handler#comment51782880_31935182Laravel 附带了默认的 ExceptionHandler,可以覆盖它。您可以通过两种方式执行此操作:
调整已实现的ExceptionHandler
Laravel 5.8 附带了一个默认的 ExceptionHandler 实现app/Exceptions/Handler.php
。这个类扩展自Illuminate\Foundation\Exceptions\Handler
这是 Laravel 的实际实现Illuminate\Contracts\Debug\ExceptionHandler
界面。通过删除父类并自己实现接口,您可以执行您想要的所有自定义异常处理。我在答案的末尾包含了 Handler 类的一个小示例实现。
注册一个新的异常处理程序
实现自定义 ExceptionHandler 的另一种方法是覆盖默认配置,可以在bootstrap/app.php
。为了覆盖 Larvel 指定的处理程序,只需为Illuminate\Contracts\Debug\ExceptionHandler::class
像这样在默认抽象之后进行抽象。
# Laravel default
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
# My custom handler
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\MyHandler::class
);
这样做的结果是App\Exceptions\MyHandler
在抛出异常的情况下调用App\Exceptions\Handler
完全被跳过。
异常处理程序示例
它很有用,我提供了一个自定义 ExceptionHandler 的小示例,以全面了解它的可能性。
namespace App\Exceptions;
use Exception;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Application;
class Handler implements ExceptionHandler
{
public function report(Exception $e)
{
Log::debug($e->getMessage());
}
public function shouldReport(Exception $e)
{
return true;
}
public function render($request, Exception $e)
{
return view('error.page');
}
public function renderForConsole($output, Exception $e)
{
(new Application)->renderException($e, $output);
}
}