Skip to main content

Lesson 6 of 7

Advanced Error Handling - Custom Handlers

Production applications must handle errors gracefully - never exposing internal details to users, always logging enough for developers to diagnose. PHP's set_error_handler() and set_exception_handler() let you take full control of error display and logging, while error_reporting and display_errors control what PHP itself shows.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Custom Error & Exception Handlers

Custom Error & Exception Handlers
<?php
declare(strict_types=1);

// ── Error reporting - dev vs production ───────────────────────
function configureErrorReporting(bool $isProduction): void {
    if ($isProduction) {
        // Show NOTHING to users - log everything
        error_reporting(E_ALL);
        ini_set("display_errors",  "0");  // hide from output
        ini_set("display_startup_errors", "0");
        ini_set("log_errors",      "1");  // write to error_log
        ini_set("error_log", __DIR__ . "/../storage/logs/php_errors.log");
    } else {
        // Development - show errors
        error_reporting(E_ALL);
        ini_set("display_errors", "1");
        ini_set("display_startup_errors", "1");
    }
}

// ── set_error_handler - intercept non-fatal PHP errors ────────
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline): bool {
    if (!(error_reporting() & $errno)) {
        return false;  // Suppressed by @, pass to standard handler
    }

    $levels = [
        E_WARNING     => "WARNING",
        E_NOTICE      => "NOTICE",
        E_USER_ERROR  => "USER_ERROR",
        E_USER_WARNING => "USER_WARNING",
        E_USER_NOTICE => "USER_NOTICE",
        E_DEPRECATED  => "DEPRECATED",
    ];
    $level = $levels[$errno] ?? "UNKNOWN";

    $message = sprintf("[%s] %s in %s on line %d", $level, $errstr, $errfile, $errline);
    error_log($message);

    // Convert errors to exceptions in development for easier debugging
    if (!IS_PRODUCTION) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }

    return true;  // true = don't run PHP's default error handler
});

// ── set_exception_handler - catch uncaught exceptions ─────────
set_exception_handler(function(Throwable $e): void {
    // Log full details
    error_log(sprintf(
        "Uncaught %s: %s in %s:%d
Stack trace:
%s",
        get_class($e),
        $e->getMessage(),
        $e->getFile(),
        $e->getLine(),
        $e->getTraceAsString()
    ));

    // Show generic message to user
    http_response_code(500);
    if (IS_PRODUCTION) {
        include __DIR__ . "/../views/errors/500.php";
    } else {
        // Development - show details
        echo "<pre>" . htmlspecialchars(
            $e::class . ": " . $e->getMessage() . "
" . $e->getTraceAsString()
        ) . "</pre>";
    }
    exit(1);
});

// ── register_shutdown_function - catch fatal errors ───────────
register_shutdown_function(function(): void {
    $error = error_get_last();
    if ($error !== null && in_array($error["type"], [E_ERROR, E_PARSE, E_CORE_ERROR], true)) {
        error_log("Fatal error: " . $error["message"] . " in " . $error["file"] . ":" . $error["line"]);
        if (!headers_sent()) {
            http_response_code(500);
        }
        echo "An unexpected error occurred. Please try again later.";
    }
});

// ── Custom exception hierarchy ─────────────────────────────────
class AppException extends RuntimeException {}
class NotFoundException       extends AppException {}
class ValidationException     extends AppException { public function __construct(public readonly array $errors, string $message = "Validation failed") { parent::__construct($message); } }
class AuthorizationException  extends AppException {}
class DatabaseException       extends AppException {}

Quick Quiz

Tip

Tip

Practice Advanced Error Handling Custom Handlers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Advanced Error Handling - Custom Handlers

Practice Task

Note

Practice Task - (1) Write a working example of Advanced Error Handling Custom Handlers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Advanced Error Handling Custom Handlers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done