To get flexibility, a user can create their own error handler function to deal with any errors raised when the script runs. Error handler can then inspect the error and decide what to do
- It might log the error in a file or database.
- Display a message to the user.
- Attempt to fix the problem and carry on.
- Clean up various files and database connections and exit.
- Or ignore the error altogether.
To use own error handler tells PHP, call set_error_handler(), passing in the name of the function:
These are the following error types which cannot be handled by a custom error handler; instead they will always be handled by PHP’s built – in error handler:
In addition, most E_STRICT errors will bypass the custom error handler, if they are raised in the file where set_error_handler() is called.
A user can optionally exclude certain types of errors from being handled by the function. To do this, pass a mask as the second argument.
For example, the following code ensures that the error handler is only called for E_WARNING or E_NOTICE errors:
set_error_handler(“myErrorHandler”, E_WARNING | E_NOTICE);
The error handler function needs to have at least two parameters, as follows:
|Errno||This parameter describes the level of the error, as an integer. This corresponds to the appropriate error level constant ( E_ERROR , E_WARNING , and so on).|
|Errstr||This parameter describes the error message as a string.|
The PHP engine passes the appropriate values to these parameters when it calls the error handler function. The function can optionally have an additional three parameters:
|Errfile||This parameter describes the filename of the script file in which the error was raised, as a string.|
|Errline||This parameter describes the line number on which the error was raised, as a string.|
|Errcontext||The parameter describes an array containing all the variables that existed at the time the error was raised. It is useful for debugging.|
Once it has finished dealing with the error, the error handler function should do one of three things:
- Exit the script, if necessary. A user can do this by calling exit() or die() , passing in an optional error message or error code to return.
- Return true (or nothing). If a user do this, PHP’s error handler is not called and the PHP engine attempts to continue execution from the point after the error was raised.
- Return false. This causes PHP’s error handler to attempt to handle the error. This is useful if a user do no t want the error handler to deal with a particular error. Depending on the error handling settings, this usually causes the error to be logged.