-
Hello everyone, I'm new to Laravel and enjoying it so far. Most of the exceptions are handled very well in the framework, but sometimes you just want a simple /**
* Attempt to execute a given callback and abort if an exception occurs.
*
*
* @param Closure $callback The callback to execute.
* @param int $statusCode The HTTP status code to use if an exception is caught (default: 500).
* @return mixed The result of the callback, if successful.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
function tryOrAbort(Closure $callback, int $statusCode = 500)
{
try {
return $callback();
} catch (\Throwable $e) {
abort($statusCode, $e->getMessage());
}
} Example Usage: Route::get('/auth/redirect/{provider}', function (string $provider) {
return tryOrAbort(fn() => Socialite::driver($provider)->redirect(), 404);
});
Route::get('/auth/callback/{provider}', function (string $provider) {
$user = tryOrAbort(fn() => Socialite::driver($provider)->user(), 404);
// ...
}); |
Beta Was this translation helpful? Give feedback.
Answered by
henzeb
Nov 13, 2024
Replies: 1 comment 1 reply
-
How about: rescue(fn() => Socialite::driver($provider)->user(), fn() => abort(404)); |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
omer-biz
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about:
https://laravel.com/docs/11.x/helpers#method-rescue