ifcastle / exceptions
一个基于模板的基本异常库,面向在Web服务中使用
v5.0.2
2024-09-08 08:11 UTC
Requires
- php: >=8.3
Requires (Dev)
- phpunit/phpunit: ^11.2
- rector/rector: ^1.2
This package is auto-updated.
Last update: 2024-09-08 08:12:55 UTC
README
PHP 8.2+ 的基础异常库(最新版本:5.0.0)
任务
- 为异常提供附加结构数据。
- 异常的方面。
- 在异常中聚合异常。
- 在全局注册表中注册异常以进行日志记录。
- 支持消息模板的概念。
- 支持异常的标签(例如用于弹性日志)。
最重要的是:让它变得简单易用 ;)
概览
错误消息模板
class MyException extends \Exceptions\BaseException { protected string $template = 'The template error message with {var}'; public function __construct($var) { parent::__construct ([ 'var' => $this->toString($var) ]); } } $exception = new MyException('string'); // should be printed: The template error message with 'string' echo $exception->getMessage();
独立的日志异常(异常注册表)
use \Exceptions\Registry; use \Exceptions\LoggableException; Registry::resetExceptionLog(); $exception = new LoggableException('this is a loggable exception'); $log = Registry::getExceptionLog(); if($log[0] === $exception) { echo 'this is loggable $exception'; }
支持异常上下文参数
基本用法
throw new BaseException('message', 0, $previous);
参数列表
// use array() $exception = new BaseException ([ 'message' => 'message', 'code' => 0, 'previous' => $previous, 'mydata' => [1,2,3] ]); ... // print_r([1,2,3]); print_r($exception->getExceptionData());
异常容器
try { try { throw new \Exception('test'); } catch(\Exception $e) { // inherits data Exception throw new BaseException($e); } } catch(BaseException $exception) { // should be printed: "test" echo $exception->getMessage(); }
容器用于更改标志 is_loggable
try { try { // not loggable exception! throw new BaseException('test'); } catch(\Exception $e) { // log BaseException, but don't log LoggableException throw new LoggableException($e); } } catch(LoggableException $exception) { // echo: "true" if($exception->getPrevious() === $e) { echo 'true'; } }
在抛出异常后追加参数
try { dispatch_current_url(); } catch(BaseException $myException) { $myException->appendData(['browser' => get_browser()]); // and throw exception on... throw $myException; }
从 BaseException 继承
class ClassNotExist extends BaseException { // This exception will be logged protected bool $isLoggable = true; /** * ClassNotExist * * @param string $class Class name */ public function __construct(string $class) { parent::__construct ([ 'template' => 'Сlass {class} does not exist', 'class' => $class ]); } }
FatalException
class MyFatalException extends BaseException { // This exception has aspect: "fatal" protected bool $isFatal = true; }
调试数据
class MyException extends BaseException { public function __construct($object) { $this->setDebugData($object); parent::__construct('its too bad!'); } }