使用register_shutdown_function()处理PHP中的致命错误 [英] Handle fatal errors in PHP using register_shutdown_function()

查看:179
本文介绍了使用register_shutdown_function()处理PHP中的致命错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据对这个答案的评论可以通过关闭功能,不能使用 set_error_handler()



我找不到如何确定是否由于致命错误或由于脚本到达结束而关闭。



此外,调试回溯功能似乎在关闭功能中被停用,使得记录致命错误发生的堆栈跟踪非常没用。



所以我的问题是:最好的反应方法是什么致命的错误(特别是未定义的函数调用),同时保持创建正确的追溯的能力?

解决方案

r我:

  function shutdown(){
$ error = error_get_last();
if($ error ['type'] === E_ERROR){
//致命错误发生
}
}

register_shutdown_function('关掉');

spl_autoload_register('foo');
//抛出一个没有被捕获的LogicException,所以触发一个E_ERROR

但是,你可能已经知道了,但只是为了确保:您无法以任何方式从E_ERROR恢复。



至于回溯,您不能... (在大多数情况下,一个致命的错误,特别是未定义的功能错误,你并不需要它,确定它发生的文件/行是足够的。在这种情况下,回溯是无关紧要的。 / p>

According to the comment on this answer it is possible to catch Fatal Errors through a shutdown function which cannot be caught using set_error_handler().

However, I couldn't find out how to determine if the shutdown has occured due to a fatal error or due to the script reaching its end.

Additionally, the debug backtrace functions seem to be defunct in the shutdown function, making it pretty worthless for logging the stack trace where the Fatal Error occured.

So my question is: what's the best way to react on Fatal Errors (especially undefined function calls) while keeping the ability to create a proper backtrace?

解决方案

This works for me:

function shutdown() {
    $error = error_get_last();
    if ($error['type'] === E_ERROR) {
        // fatal error has occured
    }
}

register_shutdown_function('shutdown');

spl_autoload_register('foo'); 
// throws a LogicException which is not caught, so triggers a E_ERROR

However, you probably know it already, but just to make sure: you can't recover from a E_ERROR in any way.

As for the backtrace, you can't... :( In most cases of a fatal error, especially Undefined function errors, you don't really need it. Pinpointing the file/line where it occured is enough. The backtrace is irrelevant in that case.

这篇关于使用register_shutdown_function()处理PHP中的致命错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆