wikimedia/normalized-exception
最新稳定版本:v2.1.1
Composer 安装命令:
composer require wikimedia/normalized-exception
包简介
A helper for making exceptions play nice with PSR-3 logging
README 文档
README
NormalizedException
A minimal library to facilitate PSR-3-friendly exception handling.
Additional documentation about the library can be found on MediaWiki.org.
Usage
The NormalizedException library provides an INormalizedException interface that exception classes can use to support a standardized way of logging their error messages in a PSR-3 compatible manner.
If you don't care about the exception class, you can use the standard implementation:
use Wikimedia\NormalizedException\NormalizedException; throw new NormalizedException( 'Invalid value: {value}', [ 'value' => $value ] );
use Wikimedia\NormalizedException\INormalizedException; try { mightThrow(); } catch ( INormalizedException $e ) { $psr3Logger->error( $e->getNormalizedMessage(), $e->getMessageContext() ); echo 'Error: ' . $e->getMessage(); }
To make a specific exception class normalized, if it's constructed from a message and optionally an error code and a previous exception (like most PHP core exceptions), you can use a trait and a default constructor provided by that trait:
use Exception use Wikimedia\NormalizedException\INormalizedException; use Wikimedia\NormalizedException\NormalizedExceptionTrait; class MyException extends Exception implements INormalizedException { use NormalizedExceptionTrait { NormalizedExceptionTrait::normalizedConstructor as __construct; } }
throw new MyException( 'Invalid value!' ); throw new MyException( 'Invalid value: {value}', [ 'value' => $value ] ); throw new MyException( 'Invalid value: {value}', [ 'value' => $value ], /* code */ -1, $previous );
Exceptions with different parameters need their own constructor:
use Wikimedia\NormalizedException\INormalizedException; use Wikimedia\NormalizedException\NormalizedExceptionTrait; class MyException extends SomeException implements INormalizedException { use NormalizedExceptionTrait; public function __construct( string $normalizedMessage, array $messageContext = [], $otherParam1, $otherParam2 ) { // these properties are defined by the trait and must be set $this->normalizedMessage = $normalizedMessage; $this->messageContext = $messageContext; // replaces the PSR-3 tokens $message = self::getMessageFromNormalizedMessage( $normalizedMessage, $messageContext ); parent::__construct( $message, $otherParam1, $otherParam2 ); } }
Running tests
composer install --dev
composer test
History
This library was split out of MediaWiki changeset 670465 during the MediaWiki 1.37 development cycle.
统计信息
- 总下载量: 365.75k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 1
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-07-01