In Laravel framework whenever you try to fetch some data from your eloquent model, if an exception occurs, it'll throw aModelNotFoundException
. In my project I need to catch this exception and redirect user to specific route.
the solution that I've ended up is like this:
try{
$foundUser = $this->user->whereId($id)->firstOrFail();
}catch(ModelNotFoundException $e){
throw new NonExistantUserException;
}
I know that I can put my redirect code inside the catch block, however I'm already catching these sort of exceptions in global.php:
App::error(function(NonExistantUserException $e)
{
return Redirect::back()->WithInput();
});
I want to know is there any way to say, for example no matter what kind of exception would occur inside try block I want to catch it as NonExistantUserException
just for this try block!
I'm asking because catching an exception an throw another one. seems a bad practice to me.
Thanks in advanced.
Absolutely not bad practice and even common practice. But you should not simply discard the previous exception as it might be useful for debugging purposes.
<?php
try {
$foundUser = $this->user->whereId($id)->firstOrFail();
} catch (ModelNotFoundException $e) {
throw new NonExistentUserException(
"Could not find user for '{$id}'.",
null,
$e // Keep previous exception.
);
}
This ensures that you have the full chain of exceptions at your disposal. Other than that your approach looks good to me.