Repository navigation
|
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 errorIt 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? |
Answered by
crynobone
Feb 20, 2025
Replies: 1 comment
|
See |
0 replies
Answer selected by
nagi1
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See
rescue()helper.