sanmai / trycatch
Exception-handling callable wrapper
Installs: 9 729
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 1
Requires
- php: ^7.0 || ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- infection/infection: >=0.1
- phan/phan: >=1.0
- php-coveralls/php-coveralls: ^2.0
- phpstan/phpstan: >=0.1
- phpunit/phpunit: ^8 || ^6 || ^9
This package is auto-updated.
Last update: 2021-05-21 02:10:49 UTC
README
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