Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Error Handling set_error_handler() Function



The PHP Error Handling set_error_handler() function is used for program error management. It lets you handle errors in your own way rather to depending on PHP's built-in error messages. This improves the security and usefulness of your program. Use set_error_handler() to tell PHP to use a custom function you created to handle errors.

It may address a number of problems including alerts and warnings. You can easily debug your apps using this function. Important error data are also hidden from users. This makes the process of developing more secure and efficient websites much easier.

You can specify what should happen in the case of an error by setting a custom error handler. For example, you can say that the error should be logged, that the developer should be emailed, or that the user should get a helpful message. You can even stop the script from running by using commands like exit() inside the error handler, if required.

It is important to note that set_error_handler() does not work with certain important errors, like E_ERROR or E_PARSE. These errors will be handled by PHP's built-in error handling system.

Syntax

Below is the syntax of the PHP Error Handling set_error_handler() function −

callable set_error_handler ( 
   ?callable $handler, 
   int $error_levels = E_ALL 
);

Parameters

Here are the parameters of the set_error_handler() function −

  • $handler: (Required) It is a user-defined function (callback) to handle errors. If null is passed, it resets the error handler to PHP's default.

  • $error_levels: (Optional) It determines which error levels will result in the handler, just like the error_reporting setting. The default value is E_ALL.

Here is the syntax for the $handler −

bool handler(
   int $errno,
   string $errstr,
   string $errfile = ?,
   int $errline = ?,
   array $errcontext = ?
)

Here are the parameter's description for the above syntax −

  • 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

The set_error_handler() function returns the error handler (if any) that was previously defined. Null is returned if the built-in error handler is used. This function will return an indexed array containing the class and the method name if the previous error handler was a class method.

PHP Version

First introduced in core PHP 4.0.1, the set_error_handler() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

The below program defines a simple custom error handler function called errorHandlerFunc. The function is used to display error messages and generates a notification when an undefined variable is accessed. The custom error handler is set using PHP Error Handling set_error_handler() function.

<?php
   // Custom error handler function
   function errorHandlerFunc($errno, $errstr) {
      echo "Error: [$errno] $errstr\n";
   }
   
   // Set the custom error handler
   set_error_handler("errorHandlerFunc");
   
   // Trigger an error
   echo $undefined_variable;
?>

Output

Here is the outcome of the following code −

Error: [2] Undefined variable $undefined_variable

Example 2

In this example, the custom error handler detects warnings (e.g. trying to open a file that does not exist). The errorHandlerFunc function prints the error message once it has determined whether the problem is a warning. The handler is set with the help of the set_error_handler() function.

<?php
   // Custom error handler function
   function errorHandlerFunc($errno, $errstr) {
      if ($errno == E_WARNING) {
         echo "Warning: $errstr\n";
      }
   }
   
   // Set custom handler 
   set_error_handler("errorHandlerFunc");
   
   // Trigger a warning
   $file = fopen("non_existent_file.txt", "r"); 
?> 

Output

This will generate the below output −

Warning: fopen(non_existent_file.txt): Failed to open stream: No such file or directory

Example 3

In this example, the custom error handler (advancedErrorHandler) records an error message and handles a variety of error types, such as alerts and warnings. If a fatal error (E_ERROR) be raised, the script ends using exit(). The handler (E_ALL) handles all error levels.

<?php
   // Custom error handler function
   function errorHandlerFunc($errno, $errstr, $errfile, $errline) {
      if ($errno == E_WARNING) {
         echo "Warning: $errstr<br>";
      } elseif ($errno == E_NOTICE) {
         echo "Notice: $errstr<br>";
      } else {
         echo "Unknown error type: $errno<br>";
      }

      // Stop script execution for fatal errors
      if ($errno == E_ERROR) {
         echo "Fatal error occurred! Terminating the script.";
         exit();
      }
   }

   // Set custom handler 
   set_error_handler("errorHandlerFunc", E_ALL);

   // Trigger a warning
   echo $undefined_variable;  

   // Trigger a fatal error
   trigger_error("This is a fatal error", E_ERROR);
?> 

Output

This will create the below output −

Notice: Undefined variable: undefined_variable
Fatal error occurred! Terminating the script.

Example 4

This code will demonstrate you how to write your own PHP error handler. It defines a function called errorHandlerFunc() to handle issues in a particular manner, like showing the file and line number where the problem occurred along with a custom problem message. This custom error handler is set using the set_error_handler() function.

<?php
   function errorHandlerFunc($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("errorHandlerFunc");
   $test = 0;

   //trigger error
   if ($test >  -1) {
      trigger_error("A custom error has been triggered");
   }
?> 

Output

Following is the output of the above code −

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