无法捕获symfony FatalErrorException [英] Can't catch symfony FatalErrorException

查看:128
本文介绍了无法捕获symfony FatalErrorException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

try {
    $var = $object->getCollection()->first()->getItem()->getName();
} catch(\Exception $e) {
    $var = null;
}

当然我有通信变量名和方法名。这只是演示。

Of course i have communicative variable and method names. This is just demonstration.

因此,如果我的集合为空,则Collection :: first()将返回false。然后,getItem调用将引发上面的代码不会捕获的Symfony\Component\Debug\Exception\FatalErrorException。

So if my collection is empty the Collection::first() will return false. Then the getItem call will throw a Symfony\Component\Debug\Exception\FatalErrorException which won't be catched by the code above.

我的问题是我如何才能捕获此异常?我有很多这样的长链,可以返回null。因此,我更喜欢这种方式,而不是检查每个值是否为null。

My question is that how can i catch this exception? I have long chains like this with many getters that can return null. So i prefer this way rather than checking every value for null.

推荐答案

好。我找到了一种解决方法。我使用的属性访问器组件会抛出简单的异常,而不是致命错误。

Ok. I've found a workaround. I use the property accessor component which throws simple exceptions, not fatal errors.

$pa = \Symfony\Component\PropertyAccess\PropertyAccess::createPropertyAccessor();
try {
    $var = $pa->getValue($object, 'collection[0].item.name');
} catch(\Exception $e) {
    $var = null;
}

这篇关于无法捕获symfony FatalErrorException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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