Custom PHP Error Handling with set_error_handler

PHP’s built-in set_error_handler() function allows developers to bypass standard PHP error reporting and implement custom logic for handling non-fatal errors. This article explains how the function works, outlines its syntax, demonstrates how to create a custom callback function, and discusses its limitations.

Understanding set_error_handler()

By default, PHP handles errors by displaying or logging them according to the configuration settings in php.ini. The set_error_handler() function redirects these errors to a user-defined callback function. This enables developers to log errors to a database, format error messages for user-friendly display, or convert standard PHP errors into exceptions.

Syntax

The basic syntax of the function is:

set_error_handler(callable $callback, int $error_levels = E_ALL): ?callable

Creating a Custom Error Handler Callback

The callback function registered by set_error_handler() must accept specific parameters to receive details about the error.

Callback Parameters

  1. $errno (int): The level of the error raised.
  2. $errstr (string): The error message.
  3. $errfile (string, optional): The filename where the error occurred.
  4. $errline (int, optional): The line number where the error occurred.

Code Example

Below is a practical implementation of a custom error handler that formats the error details and halts execution if the error is severe.

<?php
// Define the custom error handler function
function myCustomErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>[Error $errno]</b> $errstr in <b>$errfile</b> on line <b>$errline</b><br>";
    
    // If the error is critical, stop script execution
    if ($errno === E_USER_ERROR) {
        echo "Fatal error encountered. Terminating script.";
        exit(1);
    }

    // Return true to prevent PHP's internal error handler from running
    return true; 
}

// Register the custom error handler
set_error_handler("myCustomErrorHandler");

// Trigger a warning (non-fatal)
echo $undefined_variable;

// Trigger a custom user error
trigger_error("This is a custom user error!", E_USER_ERROR);
?>

Controlling Error Flow

The value returned by your callback function determines whether PHP’s native error handler is bypassed:

Restoring the Default Error Handler

If you only need custom error management for a specific section of code, you can restore PHP’s default handler using restore_error_handler().

set_error_handler("myCustomErrorHandler");

// Custom-handled code here

restore_error_handler(); // Reverts to the previous error handler

Limitations of set_error_handler()

While highly versatile, set_error_handler() cannot intercept all error types:

  1. Fatal Errors: It cannot catch fatal errors such as E_ERROR, E_PARSE, E_CORE_ERROR, or E_COMPILE_ERROR. For these, you must use register_shutdown_function() or try-catch blocks using standard PHP exceptions.
  2. The @ Operator: If an expression is prepended with the @ error-control operator, the error handler will still be called, but the error_reporting() function will return 0 inside the callback. To honor the @ operator, check this value first:
if (!(error_reporting() & $errno)) {
    // This error was suppressed with the @ operator
    return false;
}