如何在Symfony2中捕获ParamConverter异常? [英] How to catch ParamConverter exceptions in Symfony2?

查看:91
本文介绍了如何在Symfony2中捕获ParamConverter异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我遇到的例外情况:

Here is the exception I got:


尽管期望至少有一行,但未找到查询结果。

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

当在数据库中找不到用户ID时,我基本上得到了该异常。
这是我的路线:

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){
    // .. 
}

我知道我可以使用内核事件异常来处理此问题,但是有没有更简单的方法来捕获ParamConverter生成的异常?

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?

推荐答案

在某些情况下,如果找不到对象,则手动引发异常很有用。如果未找到实体,则可以通过向参数添加默认值来告诉操作跳过抛出异常。

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.

示例:

public function showUser(User $user = null) {
    if (empty($user)) {
        throw new CustomExceptionYouWant();
    }
    ...
}        

这篇关于如何在Symfony2中捕获ParamConverter异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆