wikimedia / normalized-exception
A helper for making exceptions play nice with PSR-3 logging
Requires
- php: >=7.4
Requires (Dev)
- mediawiki/mediawiki-codesniffer: 45.0.0
- mediawiki/mediawiki-phan-config: 0.14.0
- mediawiki/minus-x: 1.1.3
- ockcyp/covers-validator: 1.6.0
- php-parallel-lint/php-console-highlighter: 1.0.0
- php-parallel-lint/php-parallel-lint: 1.4.0
- phpunit/phpunit: 9.6.16
This package is auto-updated.
Last update: 2025-01-12 19:46:14 UTC
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.