sanmai/trycatch

This package is abandoned and no longer maintained. No replacement package was suggested.

Exception-handling callable wrapper

v0.3.2 2020-12-28 15:32 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