php 如何在 symfony 中尝试 Catch

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23731604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:53:55  来源:igfitidea点击:

How to Try Catch in symfony

phpsymfony

提问by user3383675

Situation:

情况:

//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 loads ok, getForestTrollType should be loaded ok too, but before that, it is a problem, getRandomBrokenTrollType() deliberately does not exist, and then I see message in console:

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/ $ _

it should be: WARNING: TROLL ENTITY DOES NOT EXIST. and then continue; but it does not happen

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

How to check existing of a object's method?

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

采纳答案by Jan Prieser

the Exception thrown by Doctrine is called Doctrine\ORM\EntityNotFoundExceptionand you are catching EntityNotFoundException.

Doctrine 抛出的 Exception 被调用Doctrine\ORM\EntityNotFoundException并且您正在捕获EntityNotFoundException.

Thats a difference, the namespace matters.

那是不同的,命名空间很重要。

to debug this, catch Exceptioninstead and observe the type of the actual exception. then replace it.

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

回答by Jay Sheth

if you're trying to catch any exception, you should use a backslash before "Exception".

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

E.g.:

例如:

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

If you don't use a backslash, the exception won't be caught. This is due to how namespaces are used in PHP / Symfony.

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

回答by Vivex

Exception Type is - \Doctrine\ORM\EntityNotFoundExceptionDon`t forget starting "\" Example -

异常类型是 - \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/>";
    }