当代理找不到参考文件时,如何抑制MongoDDException

Mad*_*rco 5 doctrine-odm

我们正在使用Symfony2 / DoctrineOdm / MongoDB,并且在执行以下操作时:

if ($doc.referenceOne != null) { ... }

$doc.referenceOne包含MongoDbRef点到已删除/丢失的文件,这个学说代理对象提出了MongoDBException。

可以告诉Proxy返回null而不是引发异常?


详细说明:

我们的文件:

class User {
    /* @MongoDB\ReferenceOne( ... ) */
    private $photo;
}
Run Code Online (Sandbox Code Playgroud)

如果$ photo包含MongoDbRef,但是文档丢失/删除,

当我们if ($user.photo) { ... }教义时会引发MongoDBException:

The "Proxies\DocumentPhotoProxy" document with identifier "4fd8b3ef732bafab7b000000" could not be found
Run Code Online (Sandbox Code Playgroud)

我们想抑制异常,因为我们的应用程序可以处理该变量中的空值。

(我们可以简单地记录该错误,而异常会传播到500页并中断我们的服务)

eym*_*men 3

编辑 2:学说扩展参考完整性也有帮助。它会自动取消无效引用。您可以在其 GitHub 存储库上找到更多信息: https: //github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/reference_integrity.md以及 Symfony2 集成: https: //github.com/stof/StofDoctrineExtensionsBundle

编辑:我无法理解您是否指的是 twig 模板或 php.ini。下面您将找到 twig 的解决方案,但如果您的问题是关于 php,try...catch为 getter 添加一个块可能会帮助您解决问题。

我不知道您是否已经找到解决方案,但如果其他人需要这个解决方案,我已经使用了一个(肮脏的)解决方案:

Twig_Template通过在主配置文件中定义自定义类来覆盖类 ( config.yml)

例子:

# app/config/config.yml
base_template_class: Acme\DemoBundle\Template
Run Code Online (Sandbox Code Playgroud)

getAttribute并用块覆盖该方法try...catch

<?php

namespace Acme\DemoBundle;

use Doctrine\ODM\MongoDB\DocumentNotFoundException;

abstract class Template extends \Twig_Template
{
    protected function getAttribute($object, $item, array $arguments = array(), $type = \Twig_TemplateInterface::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
    {
        try {
            $ret = parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
        } catch (DocumentNotFoundException $e) {
            $ret = null;
        }
        return $ret;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将忽略所有 DocumentNotFoundException。

但要小心,无效的引用仍然存在于您的数据库中。这只会忽略树枝模板中抛出的异常。