PHP - Function set_error_handler()



mixed set_error_handler ( callback $error_handler [, int $error_types] );

Definition and Usage

This function can be used for defining your own way of handling errors during runtime, 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.


Parameter Description
error_handler Required. Specifies the function to be run at errors. Syntax of error_handler is given below.
error_types Optional. Specifies on which errors report levels the user-defined error will be shown. Default is "E_ALL". See "PHP Error and Logging Constants:" for possible error report levels.

Error Handler Function Syntax

error_function(error_level,error_message, error_file,error_line,error_context);

Here are the paramenter's description −

  • errno − The first parameter, errno, contains the level of the error raised, as an integer.

  • errstr − The second parameter, errstr, contains the error message, as a string.

  • errfile − The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.

  • errline − The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.

  • errcontext − The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred.

Return Value

Returns a string containing the previously defined error handler (if any), or NULL on error.


Following is the usage of this function −

   //error handler function
   function customError($errno, $errstr, $errfile, $errline)
      echo "Custom error: [$errno] $errstr\n";
      echo "Error on line $errline in $errfile\n";
      echo "Ending Script";
   //set error handler
   //trigger error
   if ($test >  -1)
      trigger_error("A custom error has been triggered");

This will produce the following result −

Custom error: [1024] A custom error has been triggered
Error on line 17 in /var/www/tutorialspoint/php/test.php
Ending Script