PHP Basics
Functions in PHP
Working with Forms
Working with Files
Working with Databases
Advanced PHP Techniques
Custom error handlers in PHP allow developers to handle errors in a more flexible and controlled manner than the default PHP error handling. By creating custom error handlers, you can log errors, display user-friendly messages, or even recover from certain errors gracefully. Here’s a detailed look at how to create and use custom error handlers in PHP.

Setting a Custom Error Handler

To set a custom error handler, you use the set_error_handler() function. This function allows you to specify a user-defined function that will handle errors instead of the default PHP error handler.

Here’s a simple example of setting a custom error handler:

				
					function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Error: [$errno] $errstr - $errfile:$errline";
    echo "<br>";
    echo "Terminating PHP Script";
    die();
}

set_error_handler("myErrorHandler");

				
			

Parameters of the Error Handler Function

The custom error handler function can accept up to five parameters:

  1. $errno: The level of the error raised, as an integer.
  2. $errstr: The error message, as a string.
  3. $errfile: The filename in which the error occurred, as a string.
  4. $errline: The line number where the error occurred, as an integer.
  5. $errcontext (optional): An array that points to the active symbol table at the point the error occurred.

Error Levels

PHP provides several predefined constants for error levels. Some of the common ones include:

E_ERROR: Fatal run-time errors. These indicate errors that cannot be recovered from.

  • E_WARNING: Run-time warnings (non-fatal errors). Execution of the script is not halted.
  • E_NOTICE: Run-time notices. The script found something that might be an error, but could also happen in the normal course of running a script.
  • E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE: User-generated error message, warning message, and notice message, respectively.
  • E_ALL: All errors and warnings, except for E_STRICT prior to PHP 5.4.0.

Custom Error Handler Example

Here’s an example of a more comprehensive custom error handler that logs errors to a file and displays a user-friendly message:
				
					function customErrorHandler($errno, $errstr, $errfile, $errline) {
    $logFile = 'error_log.txt';
    $errorMessage = date('Y-m-d H:i:s') . " | Error: [$errno] $errstr in $errfile on line $errline\n";
    
    // Log error to a file
    error_log($errorMessage, 3, $logFile);
    
    // Display a user-friendly message
    if (!(error_reporting() & $errno)) {
        return;
    }

    switch ($errno) {
        case E_USER_ERROR:
            echo "<b>ERROR</b> [$errno] $errstr<br />\n";
            echo "Fatal error on line $errline in file $errfile";
            exit(1);
            break;

        case E_USER_WARNING:
            echo "<b>WARNING</b> [$errno] $errstr<br />\n";
            break;

        case E_USER_NOTICE:
            echo "<b>NOTICE</b> [$errno] $errstr<br />\n";
            break;

        default:
            echo "Unknown error type: [$errno] $errstr<br />\n";
            break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}

set_error_handler("customErrorHandler");

				
			

Restoring the Default Error Handler

To restore the default PHP error handler, you can use the ‘restore_error_handler()‘ function:
				
					restore_error_handler();

				
			

Handling Fatal Errors

Fatal errors (like syntax errors) cannot be handled by custom error handlers because they stop the script execution immediately. For such cases, you can use a shutdown function to perform cleanup tasks or log errors before the script completely halts. This is done using register_shutdown_function() along with error_get_last() to get the last error before the script shutdown.

Example:

				
					function shutdownFunction() {
    $lastError = error_get_last();
    if ($lastError && ($lastError['type'] === E_ERROR || $lastError['type'] === E_PARSE)) {
        // Log the error
        error_log("Fatal error: " . $lastError['message'] . " in " . $lastError['file'] . " on line " . $lastError['line']);
        // Display a user-friendly message
        echo "Something went wrong. Please try again later.";
    }
}

register_shutdown_function('shutdownFunction');

				
			
Custom error handlers in PHP provide a powerful way to manage and respond to errors in a controlled manner. By using custom error handlers, you can improve the robustness and user experience of your PHP applications. Remember to use these handlers to log errors for debugging purposes and to display user-friendly messages to end users, ensuring a better overall application experience.
Scroll to Top