cerbero/exception-handler

扩展Laravel异常处理器,定义如何通过服务提供者处理自定义异常。

3.0.0 2020-08-27 06:59 UTC

This package is auto-updated.

Last update: 2024-08-27 15:40:15 UTC


README

Author Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

SensioLabsInsight

这个Laravel包允许你定义当抛出特定异常时应用程序的行为。

默认情况下,Laravel通过app/Exceptions/Handler.php处理异常,但随着处理器的增加,这个类会变得杂乱无章,难以阅读和维护。

此外,外部Laravel包无法自动注册其自定义异常应如何由已安装的应用程序处理的规则。

此包允许您使用服务提供者注册自定义异常处理器,这样外部包也可以注册自己的处理器。

注意:此包利用了装饰者设计模式,允许您像往常一样继续使用Laravel默认处理器。它只是包装异常处理器以扩展其功能。

安装

通过Composer

composer require cerbero/exception-handler

如果您的Laravel版本低于5.5,请将此服务提供者在config/app.php中添加

'providers' => [
    ...
    Cerbero\ExceptionHandler\Providers\ExceptionHandlerServiceProvider::class,
]

用法

可以注册3种类型的处理器

  • 报告器,记录异常或将异常报告给外部服务(例如Sentry,Bugsnag...)
  • 渲染器,将异常渲染成HTTP响应
  • 控制台渲染器,将异常渲染到控制台

以下示例展示了如何在服务提供者的boot()方法中注册每种类型的处理器

use App\Exceptions\DebugException;
use App\Exceptions\ArtisanException;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Validation\ValidationException;

...

public function boot()
{
    // register a custom reporter to log all exceptions that are instances of - or extend - DebugException
    $this->app->make(ExceptionHandler::class)->reporter(function (DebugException $e) {
        $this->app['log']->debug($e->getMessage());
    });

    // register a custom renderer to redirect the user back and show validation errors
    $this->app->make(ExceptionHandler::class)->renderer(function (ValidationException $e, $request) {
        return back()->withInput()->withErrors($e->errors());
    });

    // register a custom console renderer to display errors to the console and stop the propagation of other exceptions
    $this->app->make(ExceptionHandler::class)->consoleRenderer(function (ArtisanException $e, $output) {
        $output->writeln('<error>' . $e->getMessage() . '</error>');
        return true;
    });
}

处理器基本上是一个回调,它接受要处理的异常作为第一个参数。您可以通过省略异常类型或类型提示Exception来注册一个全局处理器。

与报告器不同,渲染器还接受第二个参数:如果是渲染器,则是一个Illuminate\Http\Request实例;如果是控制台渲染器,则是一个Symfony\Component\Console\Output\OutputInterface实例。

还需要注意的是,对于异常的所有已注册处理器,都会被调用,直到其中一个返回一个真值,在这种情况下,异常传播停止。

变更日志

请参阅CHANGELOG以获取有关最近更改的更多信息。

测试

composer test

贡献

请参阅CONTRIBUTINGCONDUCT以获取详细信息。

安全

如果您发现任何安全相关的问题,请通过电子邮件andrea.marco.sartori@gmail.com联系,而不是使用问题跟踪器。

鸣谢

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。