【问题标题】:PHP: set_exception_handler not working for error thrown in set_error_handler callbackPHP:set_exception_handler 不适用于 set_error_handler 回调中抛出的错误
【发布时间】:2014-10-24 10:08:47
【问题描述】:

我有以下代码来设置我的错误/异常处理程序:

// Set the exception handler
set_exception_handler(function($e) {
    echo 'Exception';
});

// Set the error handler
set_error_handler(function($code, $message, $file, $line) {
    throw new ErrorException($message, 0, $code, $file, $line);
});

我读过很多文章,都说在 set_error_handler 回调函数中抛出异常。这应该意味着我只需要处理异常。但是 set_exception_handler 回调函数从未被调用,而是我收到警告:

警告:带有消息的未捕获异常“ErrorException”...

请注意,我使用的是 PHP 5.4。

【问题讨论】:

    标签: php exception-handling


    【解决方案1】:

    我尝试运行下面的 PHP 脚本,它运行良好。

    // set the exception handler
    set_exception_handler(function($e) {
      echo ' Exception';
    });
    
    // set the error handler
    set_error_handler(function($code, $message, $file, $line) {
      echo " Error [$message]";
      throw new ErrorException($message, 0, $code, $file, $line);
    },-1);
    
    // trigger error
    trigger_error('My own error.',E_USER_ERROR);
    

    返回:

    错误 [我自己的错误。] 异常

    它和你的完全一样。我找不到你提供的代码有什么问题,问题可能不在它之外吗?

    【讨论】:

    • 感谢您的示例运行良好。但是,如果您尝试执行“require 'DoesNotExist.php';”而不是“trigger_error(...);”它将调用错误处理程序而不是异常处理程序。
    • PHP 手册:“require 与 include 相同,但失败时也会产生致命的 E_COMPILE_ERROR 级别错误。”,因此错误消息是因为在执行代码之前发出编译错误。使用“包含”来处理异常处理程序。有一种方法可以让它发挥作用。制作一个没有错误并“包含”另外两个 PHP 文件的 php 文件: 1. 您的错误处理程序。 2.要调试的文件。这样,您的错误处理例程就已在编译要调试的文件之前执行。
    猜你喜欢
    • 2012-01-21
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多