Skip to content

Instantly share code, notes, and snippets.

@semiherdogan
Last active January 30, 2023 13:07
Show Gist options
  • Save semiherdogan/fb8f91b274ad7b97f071627d12901320 to your computer and use it in GitHub Desktop.
Save semiherdogan/fb8f91b274ad7b97f071627d12901320 to your computer and use it in GitHub Desktop.
Php attempt function

Php Attempt Function

Usage

[$result, $exception] = attempt(function() {
    throw new \Exception('hello exception');
});

if ($exception){
  // Do something with exception
}

OR if you don't care about exception, you can use it like below:

[$result] = attempt(function() {
    return 3;
});
<?php
/**
* @param \callable $callable
* @return array<mixed|null, \Throwable|null>
*/
function attempt(\callable $callable): array
{
$result = null;
$exception = null;
try {
$result = $callable();
} catch (\Throwable $t) {
$exception = $t;
}
return [$result, $exception];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment