PHP | set_error_handler() Function

PHP set_error_handler() Function


Hello dear readers! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we are going to be discussing about the PHP set_error_handler() Function.

The set_error_handler() function is used in defining your own way of handling errors during runtime, for example in applications in which you need to do a cleanup of data and files when a very critical error takes place, or when you need to trigger an error under some certain conditions.

Syntax

Following below is the syntax to use this function -

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

Following are the parameter's description -

  • error_level - This parameter contain the level of the error raised, as an integer.
  • error_message - It contains the error message as string.
  • error_file - This parameter contains the file name that the error was raised in, as a string.
  • error_line - This parameter contains the line number the error was raised at, which is an integer.
  • error_context - It contains an array that points to the active symbol table at the point the error occurred.


Parameter Details

Sr.NoParameter & Description
1

error_handler(Required)

It specifies the function to be run at errors. Syntax of error_handler is given below.

2

error_types(Optional)

It 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.


Return Value

This PHP function returns a string containing previously defined error handler (if any), or NULL on error.

Example

Try out the below example -

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

Output

When the above code is executed, it will produce the following result -

Custom error: [1024] A custom error has been triggered Error on line 16 
in /home/cg/root/1531703/main.php 
Ending Script


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about the set_exception_handler() Function in PHP.

Do feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.