Skip to content

Commit dcbf56e

Browse files
authored
feat: add rescue function for exception handling with default values (#843)
* feat: add rescue function for exception handling with default values * refactor: rename report parameter to exceptionHandler in rescue function --------- Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com>
1 parent d7dd15e commit dcbf56e

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

src/Functions.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
use RuntimeException;
5050
use stdClass;
5151
use Stringable;
52+
use Throwable;
5253
use UnitEnum;
5354

5455
use function Hyperf\Collection\value;
@@ -482,6 +483,30 @@ function ($response) use ($headers) {
482483
);
483484
}
484485

486+
/**
487+
* Catch a potential exception and return a default value.
488+
*
489+
* @template TValue
490+
* @template TFallback
491+
*
492+
* @param callable(): TValue $callback
493+
* @param (callable(Throwable): TFallback)|TFallback $rescue
494+
* @param Closure(Throwable): void|null $exceptionHandler
495+
* @return TValue|TFallback
496+
*/
497+
function rescue(callable $callback, mixed $rescue = null, ?Closure $exceptionHandler = null)
498+
{
499+
try {
500+
return $callback();
501+
} catch (Throwable $e) {
502+
if ($exceptionHandler) {
503+
$exceptionHandler($e);
504+
}
505+
506+
return value($rescue, $e);
507+
}
508+
}
509+
485510
/**
486511
* Get / set the specified session value.
487512
*

0 commit comments

Comments
 (0)