aivo / exceptions
异常
1.0.0
2016-10-25 19:45 UTC
Requires
- psr/log: ^1.0
This package is auto-updated.
Last update: 2024-09-19 09:48:23 UTC
README
BaseException 是一个抽象类。
安装
运行
composer require aivo/exceptions
或者编辑 composer.json 并添加
"require": { "aivo/exceptions": "^1" }
函数声明
\Aivo\BaseException::__construct ([\Psr\Log\LoggerInterface $logger = null, $previous = null, $previousLevel = null])
####\Psr\Log\LoggerInterface $logger 一个与 PSR-3 兼容的对象。如果提供,它将在异常发生时调用与错误级别匹配的日志方法。可以通过使用 $\Aivo\BaseException->setLogger(\Psr\Log\LoggerInterface $logger) 和 $\Aivo\BaseException->log() 在对象实例化后添加日志记录器。
####\Exception $previous 由于无法在运行时添加前一个异常,因此必须在创建新的 BaseException 对象时添加。
####string $previousLevel 如果提供,它将使用此级别记录前一个异常。这对于记录不扩展 \Aivo\BaseException 的异常很有用,例如 PDOException。
扩展对象
建议为每个需要发送的消息和代码创建一个新类。每个代码也应唯一,最好是在全局范围内。这是因为错误消息可能会随时更改,因此应用程序不应依赖于实际描述文本。
捕获对象
public function responseException(\Exception $exception, Response $response) { if ($exception instanceof \Aivo\BaseException) { $data = $exception->__toArray(); $httpCode = $exception->getHttpCode(); } else { $data = [ 'class' => get_class($exception), 'error' => $exception->getCode(), 'message' => $exception->getMessage(), ]; $httpCode = 409; } return $response->withJson($data) ->withStatus($httpCode); }
记录前一个异常
要记录前一个异常(在构造函数中提供),只需添加一个带有期望级别的第三个参数。级别必须符合 PSR-3 标准。例如
try { throw new \Exception('Super secreta'); } catch (\Exception $e) { throw new \Aivo\Exceptions\Word\NotFound( $this->logger(), $e, \Aivo\BaseException::ERROR ); }
作者
Matias Pino - mpino@aivo.co
此项目使用 语义版本控制 2.0.0