Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch different Exception types

I have a very simple function to check whether an Entity exists in a bundle:

public function checkExists($bundle, $val)
{
    try{
       $this->em->getRepository($bundle.':'.$val);
    }catch (MappingException $e){
        return false;
    }

    return true;
}

So I have the following cases:

Input                        |    Expected    |    Actual
'AppBundle', 'Company'       |    true        |    true
'AppBundle', 'NONEXISTANT'   |    false       |    false (MappingException caught)
'NONEXISTANT', 'Company'     |    false       |    500 (ORMException not caught)
'NONEXISTANT', 'NONEXISTANT' |    false       |    500 (ORMException not caught)

So I see that the problem is that there are different exceptions thrown, but how could I return false for either of the cases of one part non-existant? Is there a "general" way to catch exceptions in symfony as catch (Exception $e) with use Symfony\Component\Config\Definition\Exception\Exception; does not catch it.

like image 346
PrimuS Avatar asked Jul 16 '26 19:07

PrimuS


1 Answers

There's a couple of things to do: You can catch all exceptions firstly, then you can handle each one differently:

public function checkExists($bundle, $val)
{
    try{
       $this->em->getRepository($bundle.':'.$val);
    } catch (\Exception $e){ // \Exception  is the global scope exception
        if ($e instanceof MappingException || $e instanceof ORMException) {
            return false;
        } 
        throw $e; //Rethrow it if you can't handle it here.
    }

    return true;
}

Alternatevely have multiple catches:

 public function checkExists($bundle, $val)
{
    try{
       $this->em->getRepository($bundle.':'.$val);
    } catch (MappingException $e){
       return false;
    } catch (ORMException $e) {
       return false;
    }  //Other exceptions are still unhandled.

    return true;
}

If you're using PHP 7.1 + then you can also do:

public function checkExists($bundle, $val)
{
    try{
       $this->em->getRepository($bundle.':'.$val);
    } catch (MappingException | ORMException $e){ //Catch either MappingException or ORMException 
       return false;
    }  //Other exceptions are still unhandled.

    return true;
}
like image 59
apokryfos Avatar answered Jul 18 '26 08:07

apokryfos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!