PHP - Error Handling
PHP provides functions for error handling. They allow us to define our own error handling rules. This also allows us to change and enhance error reporting to suit our needs. The error reporting functions allow us to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.
Defining Custom Error Handling Function
The PHP set_error_handler() function is used to set 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)
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...
Defining Custom Exception Handling Function
The PHP set_exception_handler() function is used to set a user-defined exception handler function. The script will stop executing after the exception handler is called.
Syntax
set_exception_handler(callback)
Parameters
callback |
This handler function requires one parameter which is the exception object that is thrown. Before PHP 7, The signature of this handler function was: handler(Exception $ex): void Since PHP 7, most errors are reported by throwing Error exceptions, which is caught by the handler as well. Both Error and Exception implements the Throwable interface. Since PHP 7, The signature of this handler function is: handler(Throwable $ex): void NULL can be passed to reset this handler to its default state. |
Return Value
Returns the previously defined exception handler, or null on error. If no previous handler was defined, null is also returned.
Example: set_exception_handler() example
The example below shows the usage of set_exception_handler() function.
<?php //two user-defined exception handler functions function myException($e) { echo "Exception: ".$e->getMessage(); } //sets user-defined exception handler function set_exception_handler("myException"); //throw exception throw new Exception("Uncaught exception occurred!"); echo "This will not be executed.\n"; ?>
The output of the above code will be:
Exception: Uncaught exception occurred!
PHP Errors and Logging Constants
The constants below are always available as part of the PHP core.
Value | Constant | Type | Description |
---|---|---|---|
1 | E_ERROR | Integer | Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. |
2 | E_WARNING | Integer | Run-time warnings (non-fatal errors). Execution of the script is not halted. |
4 | E_PARSE | Integer | Compile-time parse errors. Parse errors should only be generated by the parser. |
8 | E_NOTICE | Integer | Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. |
16 | E_CORE_ERROR | Integer | Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. |
32 | E_CORE_WARNING | Integer | Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. |
64 | E_COMPILE_ERROR | Integer | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. |
128 | E_COMPILE_WARNING | Integer | Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. |
256 | E_USER_ERROR | Integer | User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). |
512 | E_USER_WARNING | Integer | User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). |
1024 | E_USER_NOTICE | Integer | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). |
2048 | E_STRICT | Integer | Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. |
4096 | E_RECOVERABLE_ERROR | Integer | Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (set by set_error_handler() function), the application aborts as it was an E_ERROR. |
8192 | E_DEPRECATED | Integer | Run-time notices. Enable this to receive warnings about code that will not work in future versions. |
16384 | E_USER_DEPRECATED | Integer | User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error(). |
32767 | E_ALL | Integer | All errors, warnings, and notices. |
The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. The bitwise operators can be used to combine these values or mask out certain types of errors.
Complete PHP Error Handling Reference
For a complete reference of all PHP Error Handling functions, see the complete PHP Error Handling Reference.