I have a custom exception class that extends Exception and adds on the ability to pass back more data on what threw the exception. The problem now is if I want to catch my custom exception and a standard exception, but handle them with the same block of code, I don’t know how to do that other than create a new function (which I don’t want to do for every place I’d like to use this).
try {
} catch(QM\DebugInfoException $e) {
// I don't want to duplicate the Exception handling code up here
}catch(Exception $e){
$db->rollBack();
$return['error'] = 1;
$return['errInfo'] = array(
'code' => $e->getCode(),
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
);
// I'd rather handle both here, and just add data on to $return['errInfo']
switch ($ExceptionType) {
case 'QM\DebugInfoException':
$return['errInfo']['extraInfo'] = $e->getExtraInfo();
break;
}
}
Does anyone have any good ideas on this?
You could do a get_class($e) and that will return the string representing the class name of the exception object then use that to compare in your switch.
Another option is to put a function that encapsulates the common functionality, and call it from each of the exception blocks. That way new, unexpected exceptions not in your switch can still percolate up. I’m a big fan of explicitly catching specific exceptions.