sanmai/trycatch

Exception-handling callable wrapper

v0.3.1 2020-02-03 13:32 UTC

This package is auto-updated.

Last update: 2020-09-12 01:13:02 UTC


README

Latest Stable Version Build Status Coverage Status

Exception-handling callable wrapper for Closures and other callables.

Usage

Suppose you were passing a closure to configure some dependencies, or do another mundane task:

$object->setCallback($someCallback);

And then you suddenly find that your callback started throwing exceptions here and there. You have the callback from somewhere beyond your control, so you can't really change what it does.

Now, if you want to handle certain types of exceptions gracefully, this is how you could do that:

$retval = $object->setCallback(\TryCatch\TryCatch::wrap($yourCallback)
  ->whenFailed(function (\Exception $e, $a, $b) {
    if ($e instanceof SpecificException) {
        // handle this one gracefully
        return null;             
    } elseif ($a > $b) {
        // else check for rogue callback's arguments
    }

    throw $e;
});
// $retval will be null in case of SpecificException being caught

You can also peek into arguments, that were passed to the callback.

See tests for for additional examples.

Install

composer require sanmai/trycatch