experus/exceptions

此包已被废弃且不再维护。未建议替代包。

Laravel中处理异常的方式。

2.1.1 2017-05-03 16:38 UTC

This package is not auto-updated.

Last update: 2020-03-09 21:18:44 UTC


README

如何在更大的Laravel应用中处理异常。

安装

  • 将此包添加到您的项目中。
composer require experus/exceptions
  • 在您的\App\Exceptions\Handler类中包含\Experus\Exceptions\Dispatcher特质并删除render方法
<?php

namespace App\Exceptions;

use Experus\Exceptions\Dispatcher as DispatchesExceptions;

class Handler extends ExceptionHandler
{
    use DispatchesExceptions;

    // Rest of the handler class
}
  • 现在向您的类中添加一个名为$catchers的属性。这是一个处理程序与它们处理的异常的映射。
<?php

namespace App\Exceptions;

use Experus\Exceptions\Dispatcher as DispatchesExceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    use DispatchesExceptions;

    private $catchers = [
        // A handler can handle multiple exceptions
        \Foo\Bar\NotFoundHandler::class => [
            \Foo\Bar\UserNotFoundException::class,
            \Foo\Bar\ProductNotFoundException::class,
        ],
        // Or just one, in which case you don't need an array. It just works
        \Foo\Bar\RuntimeException::class => \Foo\Bar\RuntimeHandler::class,
    ];

    // Rest of the handler class
}

编写处理程序

设置好所有这些之后,您需要编写处理程序来处理异常。幸运的是,编写处理程序非常简单。您需要的只是一个接受\Illuminate\Http\Request和您正在处理的异常的handle方法。handle方法期望您返回一个响应,如下所示

<?php

namespace \Foo\Bar\Exceptions;

use Illuminate\Http\Request;

class HttpHandler
{
    public function handle(Request $request, \Foo\Bar\DummyException $exception)
    {
        return response()->json([
            'status' => $exception->getMessage(),
        ], 500);
    }
}

如果我的应用程序同时处理JSON响应和普通请求(视图等)怎么办?

幸运的是,我们也想到了这一点。我们提供了一个\Experus\Exceptions\Catchers\Catcher类,它会为您完成这些检查。只需扩展\Experus\Exceptions\Catchers\Catcher并实现handleWeb方法以处理常规响应,以及handleJson方法以处理API响应。

忽略某些异常

有时您可能希望让Laravel处理异常,例如,laravel框架中由auth中间件抛出的AuthenticationException默认将被不同地处理(请参阅默认处理程序上的unauthenticated方法)。

您可以通过定义一个blacklist属性简单地告诉exceptions忽略这些异常

protected $blacklist = [
    \Illuminate\Auth\AuthenticationException::class,
];

在上面的例子中,exceptions将忽略所有抛出的AuthenticationException并将它们传递给默认的Laravel异常处理程序。

未处理的异常

有时您的应用程序会遇到意外的异常。exceptions附带了一个惊人的filp/whoops包(这是Laravel之前默认附带的)。在开发中,如果您没有指定处理程序,exceptions将使用whoops进行渲染,在生产中,我们将为您委托异常到默认的Laravel异常处理程序。