How to write error handler in PHP?
If you are writing your own error handler in PHP, it is absolutely necessary to follow a few rules. Otherwise, it may break the behavior of other libraries and applications that do not expect betrayal in the error handler.
Parameters
The signature of the handler looks like this:
function errorHandler(
int $severity,
string $message,
string $file,
int $line,
array $context = null // only in PHP < 8
): ?bool {
...
}
Parameter $severity
contains the error level
(E_NOTICE
, E_WARNING
, …). Fatal errors, such as
E_ERROR
, cannot be caught with the handler, so the parameter will
never have these values. Fortunately, fatal errors have essentially disappeared
from PHP and have been replaced with exceptions.
Parameter $message
is an error message. If the html_errors
directive is enabled, special characters such as <
etc., are
written as HTML entities, so you must decode
them into plain text. However, beware, some characters are not encoded as
entities, which is a bug. The displaying of errors in pure PHP is so prone to XSS.
Parameters $file
and $line
represent the file name
and the line where the error occurred. If the error occurred within
eval()
, the $file
will be supplemented with this information.
Finally, parameter $context
contains an array of local
variables, which is useful for debugging, but has been dropped since PHP 8. To
be compatible with PHP 8, omit the parameter or give it a default value.
Return value
The return value of the handler can be null
or
false
.
The value false
says that a standard PHP handler will be called.
Depending on the configuration, it can print error, log it, etc. It will also
make it available to the error_get_last()
function.
Suppressed Errors
In PHP, errors can be suppressed (or muted) either by using the shut-up
operator @
or using error_reporting()
:
// suppress errors E_USER_DEPRECATED
error_reporting(~E_USER_DEPRECATED);
// suppress all errors when calling fopen()
$file = @fopen($name, 'r');
Even when errors are suppressed, handler is called. Therefore, it is first necessary to check whether the error is suppressed, and if so, we must end the handler:
if (($severity & error_reporting()) !== $severity) {
return false;
}
Handler must be terminated in this case with return false
to run a standard error handler. It does not print anything and does not log
(because the error is suppressed), but it ensures that the error can be returned
by error_get_last()
.
Other Errors
If the handler handles the error (for example, prints its own message, etc.),
there is no need to call a standard handler. Although it will not be possible to
get the error using error_get_last()
, this does not matter in
practice, because this function is used mainly in combination with the shut-up
operator.
If, on the other hand, the handler does not handle the error, it should
return false
to not to hide it.
Zanechat komentář