Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch ParamConverter exceptions in Symfony2?

Here is the exception I got:

No result was found for query although at least one row was expected.

I am basically getting that exception when a user id is not found in database. Here is what my route looks like:

localhost/../user/18

and the code in my controller:

public function showAction(User $user){
    // .. 
}

I know I can use the kernel event exception to handle this, but is there an easier way to catch an exception generated by the ParamConverter?

like image 434
lokiloq Avatar asked Nov 29 '13 09:11

lokiloq


2 Answers

In some cases it's useful to throw exception manually if object not found. You can tell action skip throw exception if entity not found by adding default value to param.

Example:

public function showUser(User $user = null) {
    if (empty($user)) {
        throw new CustomExceptionYouWant();
    }
    ...
}        
like image 151
Yury Tolochko Avatar answered Nov 17 '22 18:11

Yury Tolochko


You can create your user ParamConverter by implementing ParamConverterInterface and inside it, create methods you can use as a custom exception or do other processing.

This a good exemple of what you want to create Custom ParamConverter

like image 32
Amine Avatar answered Nov 17 '22 16:11

Amine