experus / exceptions
Laravel中处理异常的方式。
Requires
- php: >=5.5.9
- filp/whoops: ^2.0@dev
- illuminate/http: ^5.2
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异常处理程序。