dqsvf28682 2013-09-10 13:43
浏览 102

捕获致命的PHP错误并抛出异常

The entry point (front controller) for our software is wrapped in a try catch block which catches exceptions and then includes a PHP file to show a friendly error page, as well as emailing us about the exception. This work perfectly, however it misses PHP fatal errors which just show a HTTP 500 response. I'm trying to catch those errors in the same way as exceptions.

At the moment, we have this in the application's entry point:

try {
    // Register a shutdown handler for fatal errors
    register_shutdown_function(function() {
        $error = error_get_last();

        // Did this request throw an error that wasn't handled?
        if ($error !== null) {
            throw new Exception('PHP fatal error!');
        }
    });

    // ...normal front controller stuff
} catch (Exception $e) {
    // show fancy error screen with debug information
    include 'themes/error/500.php';
}

Here, I'm throwing an exception when PHP throws a fatal error in the hopes that it gets handled by the normal exception handling procedure. However, the exception never gets caught:

Fatal error: Uncaught exception 'Exception' with message 'PHP fatal error!'

How can I achieve what I want to do here?

  • 写回答

1条回答 默认 最新

  • dqb14659 2013-09-10 13:46
    关注

    You should not use register_shutdown_function() for that - it makes no sense since you're already at stage when script is exiting. PHP allow you to handle errors via set_error_handler() function.

    But note, you can not handle fatal errors with that (such as calling undefined functions) - and, of cause, parse error as well:

    The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线