decodelabs / exceptional
PHP 更好的异常处理
v0.4.7
2024-08-22 13:33 UTC
Requires
- php: ^8.1
- decodelabs/coercion: ^0.2
- decodelabs/glitch-support: ^0.4
- decodelabs/wellspring: ^0.1.0
- symfony/polyfill-mbstring: ^1.7
Requires (Dev)
README
PHP 更好的异常处理
Exceptional旨在提供一种根本性的增强的异常框架,将异常的意义与底层的实现功能解耦。
在DecodeLabs博客上获取新闻和更新。
安装
通过Composer安装
composer require decodelabs/exceptional
使用方法
Exceptional异常可以极大地简化您在代码中生成和抛出错误的方式,尤其是如果您正在编写共享库。
通过将您打算使用的异常名称作为对Exceptional基类的静态调用传递,可以动态创建一个基于最合适的PHP异常类的异常类,并附带一组相关接口以便更容易地捕获。
use DecodeLabs\Exceptional; // Create OutOfBoundsException throw Exceptional::OutOfBounds('This is out of bounds'); // Implement multiple interfaces throw Exceptional::{'NotFound,BadMethodCall'}( "Didn't find a thing, couldn't call the other thing" ); // You can associate a http code too.. throw Exceptional::CompletelyMadeUpMeaning( message: 'My message', code: 1234, http: 501 ); // Implement already existing Exception interfaces throw Exceptional::{'InvalidArgument,Psr\\Cache\\InvalidArgumentException'}( message: 'Cache items must implement Cache\\IItem', http: 500, data: $item ); // Reference interfaces using a path style throw Exceptional::{'../OtherNamespace/OtherInterface'}('My exception');
使用您所需的任何范围以常规方式捕获Exceptional异常
namespace MyNamespace; try { throw Exceptional::{'NotFound,BadMethodCall'}( "Didn't find a thing, couldn't call the other thing" ); } catch( \Exception | \BadMethodCallException | Exceptional\Exception | Exceptional\NotFoundException | MyNamespace\NotFoundException | MyNamespace\BadMethodCallException ) { // All these types will catch dd($e); }
特性
通过在实现接口的同一命名空间级别定义特性,可以将自定义功能自动混合到生成的异常中。
namespace MyLibrary; trait BadThingExceptionTrait { public function getCustomData(): ?string { return $this->params['customData'] ?? null; } } class Thing { public function doAThing() { throw Exceptional::BadThing( message: 'A bad thing happened', data: [ 'customData' => 'My custom info' ] ); } }