Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Try Catch in symfony

Tags:

php

symfony

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:

 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?

like image 360
user3383675 Avatar asked May 19 '14 07:05

user3383675


2 Answers

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.

like image 123
Jay Sheth Avatar answered Sep 27 '22 20:09

Jay Sheth


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

Thats a difference, the namespace matters.

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

like image 31
Jan Prieser Avatar answered Sep 27 '22 18:09

Jan Prieser