The set_error_handler Function
The set_error_handler
function sets a user-defined error handler.
The first parameter is a callback function that will be called when an error occurs.
The second optional parameter can specify the types of errors that the handler should intercept.
Syntax
set_error_handler(callable $error_handler, int $error_types = E_ALL | E_STRICT);
Example
A simple example of a custom error handler:
<?php
function customError($errno, $errstr, $errfile, $errline) {
echo "Error [$errno]: $errstr in $errfile on line $errline";
}
set_error_handler("customError");
echo $undefinedVar;
?>
Code execution result:
Error [8]: Undefined variable: undefinedVar in /path/to/file.php on line 7
Example
Handling only specific error types:
<?php
function warningHandler($errno, $errstr) {
if ($errno === E_WARNING) {
echo "Warning captured: $errstr";
}
}
set_error_handler("warningHandler", E_WARNING);
strpos(); // Will cause a warning
?>
Code execution result:
Warning captured: strpos() expects at least 2 parameters, 0 given
Example
Restoring the standard error handler:
<?php
set_error_handler(null); // Restore to the standard handler
?>