PHP Tutorial PHP Advanced PHP References

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)

  • errno - The first parameter, errno, will be passed the level of the error raised, as an integer.
  • errstr - The second parameter, errstr, will be passed the error message, as a string.
  • errfile - If the callback accepts a third parameter, errfile, it will be passed the filename that the error was raised in, as a string.
  • errline - If the callback accepts a fourth parameter, errline, it will be passed the line number where the error was raised, as an integer.

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

Required. Specify the name of the function to be called when an uncaught exception occurs.

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.

ValueConstantTypeDescription
1E_ERRORIntegerFatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.
2E_WARNINGIntegerRun-time warnings (non-fatal errors). Execution of the script is not halted.
4E_PARSEIntegerCompile-time parse errors. Parse errors should only be generated by the parser.
8E_NOTICEIntegerRun-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.
16E_CORE_ERRORIntegerFatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP.
32E_CORE_WARNINGIntegerWarnings (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.
64E_COMPILE_ERRORIntegerFatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.
128E_COMPILE_WARNINGIntegerCompile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine.
256E_USER_ERRORIntegerUser-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error().
512E_USER_WARNINGIntegerUser-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error().
1024E_USER_NOTICEInteger User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error().
2048E_STRICTIntegerEnable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.
4096E_RECOVERABLE_ERRORInteger 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.
8192E_DEPRECATEDIntegerRun-time notices. Enable this to receive warnings about code that will not work in future versions.
16384E_USER_DEPRECATEDIntegerUser-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error().
32767E_ALLIntegerAll 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.


5