How to catch ParamConverter exceptions in Symfony2?

ぃ、小莉子 提交于 2019-12-23 14:21:28

问题


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?


回答1:


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();
    }
    ...
}        



回答2:


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



来源:https://stackoverflow.com/questions/20282884/how-to-catch-paramconverter-exceptions-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!