Reputation: 48101
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()
Upvotes: 17
Views: 10017
Reputation: 432
See https://www.php.net/manual/en/language.errors.php7.php
Most fatal errors can be handled with try catch finally
or with ser_exception_handler
Example:
<?php
class A{
public static $a=1;
}
try {
unset(A::$a);
} catch(\Error $e){
echo 'hello';
}
But this does not mean that this applies to all errors.
For example, through try catch
you will not catch errors E_WARNING, E_NOTICE, E_DEPRECATED
or errors caused by the trigger_error
function, but these errors are easily handled through set_error_handler
.
Upvotes: 0
Reputation: 1552
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
Upvotes: 4
Reputation: 490263
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 ofE_STRICT
raised in the file whereset_error_handler()
is called.
The register_shutdown_function()
and error_get_last()
is a decent workaround.
Upvotes: 26
Reputation: 318518
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.
Upvotes: 5