【问题标题】:How can I run the same code for a custom exception and a standard exception?如何为自定义异常和标准异常运行相同的代码?
【发布时间】: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


【解决方案1】:

你可以做一个 get_class($e) ,它会返回代表异常对象的类名的字符串,然后在你的开关中使用它来比较。

另一种选择是放置一个封装通用功能的函数,并从每个异常块中调用它。这样一来,不在您的交换机中的新的、意外的异常仍然可以渗透。我非常喜欢明确地捕获特定的异常。

【讨论】:

  • 我使用的解决方案是: if (get_class($e) == 'QM\DebugInfoException') {$return['errInfo']['extraInfo'] = $e->getExtraInfo(); }
猜你喜欢
  • 2017-04-12
  • 1970-01-01
  • 2019-06-24
  • 2021-12-29
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多