PHP set_error_handler() Function
The PHP set_error_handler() function sets a user-defined error function to handle errors in a script.
This function is used to define the way of handling errors during runtime by user, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions.
The standard PHP error handler is completely bypassed for the error types specified by error_levels unless the callback function returns false. The user-defined error handler must terminate the script, die(), if necessary. error_reporting() settings will have no effect on this function and this function will be called regardless - however the user will still be able to read the current value of error_reporting and act appropriately.
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 independent of where they were raised, and most of E_STRICT raised in the file where this function is called.
If errors occur before the script is executed the custom error handler cannot be called since it is not registered at that time.
Syntax
set_error_handler(callback, error_levels)
Parameters
callback |
Required. Specify the function with the following signature. null may be passed instead, to reset this handler to its default state. Instead of a function name, an array containing an object reference and a method name can also be used.
handler(errno, errstr, errfile, errline, errcontext)
If the function returns false then the normal error handler continues. |
error_level |
Optional. Specify the error_reporting level for the current script. It takes on either a bitmask, or named constants which are described in the predefined constants. Using named constants is recommended to ensure compatibility for future versions. Default is "E_ALL". |
Return Value
Returns the previously defined error handler (if any). If the built-in error handler is used null is returned. If the previous error handler was a class method, this function will return an indexed array with the class and the method name.
Example: set_error_handler() example
The example below shows the usage of set_error_handler() function.
<?php //a user-defined error handler function function myErrorHandler($errno, $errstr, $errfile, $errline) { echo "<b>My ERROR</b> [$errno] $errstr<br>\n"; echo "Error on line $errline in file $errfile<br>\n"; echo "Aborting...<br>\n"; } //setting user-defined error handler function set_error_handler("myErrorHandler"); $test = 100; //triggering user-defined error handler function if ($test==100) { trigger_error("A custom error has been triggered"); } ?>
The output of the above code will be:
My ERROR [1024] A custom error has been triggered Error on line 20 in file index.php Aborting...
❮ PHP Error Handling Reference