php - Catch different Exception types -
i have simple function check whether entity exists in bundle:
public function checkexists($bundle, $val) { try{ $this->em->getrepository($bundle.':'.$val); }catch (mappingexception $e){ return false; } return true; }
so have 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 see problem there different exceptions thrown, how return false either of cases of 1 part non-existant? there "general" way catch exceptions in symfony catch (exception $e)
use symfony\component\config\definition\exception\exception;
not catch it.
there's couple of things do: can catch exceptions firstly, can handle each 1 differently:
public function checkexists($bundle, $val) { try{ $this->em->getrepository($bundle.':'.$val); } catch (\exception $e){ // \exception global scope exception if ($e instanceof mappingexception || $e instanceof ormexception) { return false; } throw $e; //rethrow if can't handle 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 still unhandled. return true; }
if you're using php 7.1 + can 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 still unhandled. return true; }
Comments
Post a Comment