【问题标题】:Execute default exception handler after executing custom error handle执行自定义错误句柄后执行默认异常处理程序
【发布时间】:2014-02-27 00:32:39
【问题描述】:

在 PHP 中,我使用 set_exception_handler 函数构建了一个错误处理程序。它正在执行我的自定义异常处理程序。我希望 PHP 在执行我的处理程序后也执行默认异常处理程序。这是我的代码。

function handleException( exception $e){ 
    echo $e->getMessage(); 
    restore_exception_handler(); 
} 

set_exception_handler( 'handleException');

echo $e->getMessage() 被执行,但是即使在使用restore_exception_handler 之后,默认的 PHP 异常处理程序也不会被执行。那么,我怎样才能让它工作呢?

【问题讨论】:

标签: php exception


【解决方案1】:

你应该在恢复后触发之前的异常处理程序

function handleException( exception $e){ 
    echo $e->getMessage(); 
    restore_exception_handler();
    throw $e; //This triggers the previous exception handler
} 

set_exception_handler( 'handleException');

【讨论】:

  • 哦!我没想到在处理程序中使用throw,结果浪费了很多时间
【解决方案2】:

manual 很清楚这一点:

如果在 try/catch 块中未捕获到异常,则设置默认异常处理程序。调用 exception_handler 后将停止执行。

之后就没有机会运行任何代码了。

但是,您可以直接调用它:

try {
    // some code that throws an Exception
} catch(Exception $e) {
    handleException($e);
    // .. run custom handler now
}

这里不需要使用restore_exception_handler()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多