NormalizedException

NormalizedException is a minimal PHP library to facilitate PSR-3-friendly exception handling.

Usage

Use the standard implementation:

use Wikimedia\NormalizedException\NormalizedException;

throw new NormalizedException( 'Invalid value: {value}', [ 'value' => $value ] );

Adapt existing exceptions:

use Wikimedia\NormalizedException\INormalizedException;
use Wikimedia\NormalizedException\NormalizedExceptionTrait;

class MyException extends SomeException implements INormalizedException {
    use NormalizedExceptionTrait {
		NormalizedExceptionTrait::normalizedConstructor as __construct;
	}
}

// or...

class MyOtherException extends SomeException implements INormalizedException {
	public function __construct( string $normalizedMessage, array $messageContext = [], $someOtherParameter ) {
	    // these properties are defined by the trait and must be set
		$this->normalizedMessage = $normalizedMessage;
		$this->messageContext = $messageContext;
		parent::__construct(
			self::getMessageFromNormalizedMessage( $normalizedMessage, $messageContext, $someOtherParameter )
		);
	} 
}

throw new MyException( 'Invalid value: {value}', [ 'value' => $value ] );

Integrate it with error handling:

use Wikimedia\NormalizedException\INormalizedException;

try {
	mightThrow();
} catch ( INormalizedException $e ) {
	$psr3Logger->error( $e->getNormalizedMessage(), $e->getMessageContext() );
	echo 'Error: ' . $e->getMessage();
}
Category:PHP libraries