Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set_error_handler() doesn't work for FATAL error

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()

like image 922
dynamic Avatar asked Dec 15 '11 23:12

dynamic


People also ask

How to catch fatal error in PHP?

You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.

How to avoid fatal error in PHP?

Fatal errors are fatal. Even if you were to write your own error handler or use the @ error suppression operator, E_FATAL errors will still cause the script to halt execution. The only way to handle this is to use function_exists() (and possibly is_callable() for good measure) as in your example above.

What is use of set_error_handler in PHP?

The set_error_handler() function sets a user-defined error handler function. Note: The standard PHP error handler is completely bypassed if this function is used, and the user-defined error handler must terminate the script, die(), if necessary.


2 Answers

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.

like image 70
alex Avatar answered Oct 05 '22 16:10

alex


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.

like image 34
ThiefMaster Avatar answered Oct 05 '22 18:10

ThiefMaster