如何处理Symfony2框架中实体内部的异常



我想从实体类获取一些数据。我试图使用尝试/捕获来处理问题,但它行不通(仍然给我例外屏幕)。

错误:在非对象上致电成员函数getgroup() /var/www/html/system/src/project/somebundle/entity/myentity.php line 139 500内部服务器错误-FatalErrorexception stack Trace

我该如何在实体中做类似的事情?

代码/实体:

<?php
namespace ProjectSomeBundleEntity;
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
/**
 * MyEntity
 *
 * @ORMTable(name="my_entity")
 * @ORMEntity(repositoryClass="ProjectSomeBundleEntityRepositoryMyEntityRepository")
 */
class MyEntity
{
    /**
     * @var integer
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @var string
     *
     * @ORMColumn(name="name", type="string", length=255)
     * @AssertLength(max="255")
     */
    private $name;
    /**
     * @var Item[]|Collection
     *
     * @ORMOneToMany(targetEntity="ProjectSomeBundleEntityItem", mappedBy="itemType", cascade={"remove"}, fetch="EXTRA_LAZY")
     */
    protected $items;
    // [...]

    /**
     * Get some data
     *
     * @return string
     */
    public function getSomeData()
    {
        $result = null;
        try {
            $result = $this->getName() . ' - ' . $this->getItems()->last()->getGroup()->getCode();
        }
        catch(Exception $exception) {
            $result = $this->getName();
            $logFile = fopen('/tmp/error.log', 'a');
            fwrite($logFile, $exception->getMessage());
            fclose($logFile);
        }
        return $result;
    }
}

预先感谢...

错误消息 Error: Call to a member function getGroup() on a non-object in...与您接收的无关。这意味着您试图在不是对象的东西上调用功能。

$this->getItems()->last()似乎以某种方式返回null(因为没有项目),然后您在null上调用getGroup(),这是一个非对象。

尝试调试您调用getGroup()的对象,并在调用它之前查看其所持的值。

如果要捕获该错误

    try {
        $result = $this->getName() . ' - ' . $this->getItems()->last()->getGroup()->getCode();
    }
    catch(SymfonyComponentDebugExceptionFatalErrorException $exception) {
        $result = $this->getName();
        $logFile = fopen('/tmp/error.log', 'a');
        fwrite($logFile, $exception->getMessage());
        fclose($logFile);
    }

您可以看到我已经更改了 exception 在上面的代码块中

最新更新