【问题标题】:How to Try Catch in symfony如何在 symfony 中尝试 Catch
【发布时间】:2014-07-07 01:13:08
【问题描述】:

情况:

//trollCommand.php
[...]
foreach ($trolltypes as $type) { //$type=={"Frost","RandomBroken","Forest"}
    try {
        $output->writeln($type);
        $troll={"get".$type."TrollType"}();
        $output->writeln("TEST 1");
        $troll->__load();
        $output->writeln("TEST 2");
    } catch (EntityNotFoundException $e) {
        $output->writeln("WARNING: TROLL ENTITY DOES NOT EXIST.");
        continue;
    }
    $output->writeln("TROLLING");
    do_something_with_troll($troll);
}

getFrostTrollType 加载正常,getForestTrollType 也应该加载正常,但在此之前,这是一个问题,getRandomBrokenTrollType() 故意不存在,然后我在控制台中看到消息:

 Frost
 Test 1
 Test 2
 TROLLING
 RandomBroken
 Test 1
 [Doctrine\ORM\EntityNotFoundException]  
 Entity was not found. 
 //[EXIT FROM SCRIPT]
 troll@troll-machine ~/trollSandbox/ $ _

应该是:警告:巨魔实体不存在。然后继续;但它不会发生

如何检查对象的方法是否存在?

【问题讨论】:

  • 什么不会发生?警告还是继续?还是两者都没有?

标签: php symfony


【解决方案1】:

如果您试图捕获任何异常,则应在“异常”之前使用反斜杠。

例如:

try{
    //do stuff here
}
catch(\Exception $e){
    error_log($e->getMessage());
}

如果不使用反斜杠,则不会捕获异常。这是由于名称空间在 PHP / Symfony 中的使用方式。

【讨论】:

  • 这个!对我帮助很大。
【解决方案2】:

Doctrine 抛出的异常称为Doctrine\ORM\EntityNotFoundException,而您正在捕获EntityNotFoundException

这是一个区别,命名空间很重要。

要对此进行调试,请改为捕获 Exception 并观察实际异常的类型。然后替换它。

【讨论】:

  • 我这样做了,然后我发现,我很愚蠢。我从其他脚本复制了 try catch 块以仅在新脚本中进行一些编辑,但我忘记添加行“use ... ;”...
【解决方案3】:

异常类型是 - \Doctrine\ORM\EntityNotFoundException 不要忘记开始“\” 示例 -

 try {
        $entityManager = $this->getEntityManager();
        $entityManager->remove($entity);
        $entityManager->flush(); // save to the database
    } catch (\Doctrine\ORM\EntityNotFoundException $ex) {
        echo "Exception Found - " . $ex->getMessage() . "<br/>";
    }

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 2014-12-22
    • 2012-02-26
    • 2017-02-13
    • 2015-10-04
    • 1970-01-01
    • 2010-12-25
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多