【发布时间】:2012-10-18 19:19:42
【问题描述】:
我有一个自定义异常类,它扩展了 Exception 并增加了传回有关引发异常的更多数据的能力。现在的问题是,如果我想捕获自定义异常和标准异常,但使用相同的代码块处理它们,除了创建一个新函数(我不想为每个我想使用它的地方做)。
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;
}
}
有人对此有什么好的想法吗?
【问题讨论】:
-
尝试在上面的异常处理代码中使用'throw'。它将“抛出异常”。
-
您可以完全删除第一个块。只需使用 catch(Exception $ex)。它会抓住两者。使用函数处理程序并将异常作为参数传递。
标签: php exception-handling try-catch