-
Hi Community, I’ve been thinking about adding a simple helper to handle exceptions in a safer way. The idea is to wrap a callback in a try-catch block, catch any exceptions, log them, and return a default value instead of letting the error break things. Something like this: function safe_execute(callable $callback, $default = null)
{
try {
return $callback();
} catch (\Throwable $e) {
// This log can be removed
Log::error('Error: ' . $e->getMessage(), [
'exception' => $e,
]);
return $default;
}
} Usage example: $result = safe_execute(function () {
return $serviceInterface->someMethodThatMayThrowAnException();
}, 'default_value');
dd($result); // Will print 'default_value' instead of throwing an error It seems that this can be of service to clean the code a little if you are working with something that can throw exceptions, e.g., database queries or API queries. Is this something that might go into 12.x? I’d like to open a PR with the code and tests. Is that something you would need? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
See |
Beta Was this translation helpful? Give feedback.
See
rescue()
helper.