set_error_handler() doesn't work for FATAL error

◇◆丶佛笑我妖孽 提交于 2019-11-26 17:12:17

问题


I have a simple custom error handler that writes in a error log file some useful debug infos.

it's work for everything but it's not get triggered for FATAL error.

Any way to solve this?

Currently to bypass this circumstance I have registered a shutdown function too that checks error_get_last()


回答1:


Nope, that's just a limitation of set_error_handler(); it doesn't handle all errors.

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.

The register_shutdown_function() and error_get_last() is a decent workaround.




回答2:


There are only hackish ways to solve it, e.g. by using register_shutdown_function() and then checking if an error occurred inside that function.

PHP has log_errors for a reason, you can make PHP log any error to syslog or a logfile without a single line of custom code. So using set_error_handler() for this purpose is not needed at all and should be avoided unless you need e.g. a stacktrace.




回答3:


As others have pointed out we can use register_shutdown_function() and error_get_last() in following fashion.

The below implementation will catch the errors which are not even caught by \Throwable as tested in php 7.1. It should work for previous PHP versions too. It should only be implemented in your development environment(by just adding it in your development config file) and shouldn't be done in production environment.

Implementation

register_shutdown_function(function () {
    $err = error_get_last();
    if (! is_null($err)) {
        print 'Error#'.$err['message'].'<br>';
        print 'Line#'.$err['line'].'<br>';
        print 'File#'.$err['file'].'<br>';
    }
});

Example Error

Error# Class Path/To/MyService contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Path/To/MyServiceInterface::add)
Line# 12
File# Path/To/MyService.php


来源:https://stackoverflow.com/questions/8527894/set-error-handler-doesnt-work-for-fatal-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!