A context exception interface and implementation

2.0.0 2019-09-24 09:39 UTC

This package is auto-updated.

Last update: 2021-01-18 17:24:30 UTC


Build Status Total Downloads Monthly Downloads Latest Stable Version SensioLabsInsight Code Climate Codacy Badge Scrutinizer Code Quality PRs Welcome PHPPackages Referenced By License

Exception logging proves particularly useful to monitor application failure, but as it is, cannot provide with contextual data that could help out when processing those exception logs.

This Exception interface and implementation is just a step towards providing context to exceptions allowing you to interact with such exception and log them together with the extra information you would have provided.

It goes particularly well with Monolog and global exception handling where you can directly and globally add exception context to your log (when available) which may be of virtually any nature (monolog has a lot of handler and you can add more yourself to suite your need).

In your exception handler (or just a try{}catch{}:

if ($exception instanceof ContextExceptionInterface) {
    $context = $exception->getContext();
    // now you can add this data to your monolog's context

Setting context can be achieved in several ways :

// arguable way
throw (new ContextException('Message'))->setContext($contextData);

// or more conventional
throw new ContextException('Message', 0, null, $contextData);

// or step by step (also arguable)
$exception = new ContextException;
throw $exception;

IMHO, the arguability of some of the way to provide context to exceptions does not match the usefulness they provide IRL. I'm not saying that the conventional way to throw should not be in principle preferred, but I definitely find IRL use for things like :

} catch (ContextException $e) {
    // access context
    $context = $e->getContext();
    // set context in case there is none
    // and even add more context

And from there, you get mutability so ...


ContextException can be installed using composer:

composer require "fab2s/context-exception"

If you want to specifically install the php >=7.1.0 version, use:

composer require "fab2s/context-exception" ^1

If you want to specifically install the php 5.6/7.0 version, use:

composer require "fab2s/context-exception" ^0


ContextException is tested against php 7.1, 7.2, 7.3 and 7.4


ContextException is open-sourced software licensed under the MIT license.