The Analogy: The Building's Layered Fire Response
A large building does not rely on a single response to fire. It has layers. At each doorway a local extinguisher lets someone deal with a small blaze on the spot. If that fails, sprinklers over the whole floor engage automatically for anything the local response missed. And behind it all, a fire alarm wired to the fire brigade ensures that even a fire nobody catches in time still summons a proper, recorded response rather than being ignored. A program's error handling is layered the same way: local try/catch for problems you expect, a global exception handler for anything uncaught, and a shutdown handler as the last resort for catastrophic failures that bypass everything else.
Each layer catches what the layer below it missed. The person with the extinguisher handles the wastebasket fire; the sprinklers handle the fire that spread past them; the brigade handles the blaze the sprinklers could not contain. Nothing is meant to reach the brigade that a lower layer should have handled, but the brigade must exist for the day something does. PHP's set_exception_handler is the sprinkler system -- it catches exceptions no try/catch caught -- and register_shutdown_function is the alarm to the brigade, running even after a fatal error has stopped normal execution.
A well-run building also decides who hears what. Occupants hear a calm "please leave by the nearest exit"; the fire chief gets the detailed panel showing exactly which sensor tripped, on which floor, at what time. The two audiences get different information on purpose: the public message is reassuring and generic, the operational record is complete and specific. Robust error handling makes the same split -- the user sees "something went wrong", while the log records the exception class, message, stack trace, and context an engineer needs to fix it.
The failure mode is a building that shows every occupant the raw sensor diagnostics -- flashing "SMOKE DETECTOR 4F-12 FAULT, RELAY 0x3A" at people who just need to get out -- or, worse, one whose alarm panel is switched off so failures happen in silence. In software this is the site that prints a full stack trace with file paths and database queries to every visitor, handing attackers a map of the system, or the one that suppresses all errors so failures leave no trace and go undiagnosed. The layered response exists to route each failure to the right handler and the right audience: caught where possible, escalated where not, logged always, and never leaked to the public.
Syntax or Core Structure
PHP lets you install a global error handler that converts built-in errors -- warnings, notices -- into catchable ErrorException objects, unifying them with normal exception handling.
<?php
declare(strict_types=1);
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
throw new ErrorException($message, 0, $severity, $file, $line);
});
try {
$result = 10 % 0;
} catch (\Throwable $e) {
echo 'caught: ', get_class($e), "\n";
}
try {
$arr = [];
echo $arr['missing'];
} catch (ErrorException $e) {
echo 'caught warning as exception: ', $e->getMessage(), "\n";
}
restore_error_handler();
Output:
caught: DivisionByZeroError
caught warning as exception: Undefined array key "missing"
The set_error_handler callback rethrows any built-in error as an ErrorException. Modulo by zero raises a DivisionByZeroError -- an engine Error, caught here by the Throwable handler. Accessing a missing array key normally emits only a warning, but the handler turns it into an ErrorException the catch can see, reporting Undefined array key "missing". This unification means even low-level warnings can be handled with the same try/catch discipline as everything else, rather than being silently ignored.
Technical Depth: The Three Global Handlers
What each handler is for
PHP provides three global hooks, each covering a different failure layer. Knowing which fires when is the key to a complete strategy.
| Function | Catches | Runs when |
|---|---|---|
set_error_handler | Warnings, notices, non-fatal errors | A built-in error is raised |
set_exception_handler | Uncaught exceptions | An exception escapes all try/catch |
register_shutdown_function | Fatal errors (via error_get_last) | Script ends, including on fatal error |
The global exception handler
set_exception_handler is the last resort for any exception no try/catch caught. It is where you log the full detail and present a single safe message, rather than letting PHP print a raw trace.
<?php
declare(strict_types=1);
set_exception_handler(function (\Throwable $e): void {
echo 'handler logged: ', get_class($e), ' - ', $e->getMessage(), "\n";
echo "user sees: Something went wrong.\n";
});
throw new RuntimeException('database unreachable');
Output:
handler logged: RuntimeException - database unreachable
user sees: Something went wrong.
The RuntimeException is thrown with no surrounding try/catch, so it propagates all the way out and the global handler runs. In a real application the first line would go to a log file or monitoring service with full context, and only the second, generic line would reach the browser. This is the single place to guarantee that no uncaught exception ever escapes as a raw stack trace to the user.
The shutdown function for fatal errors
Some errors -- a fatal error, running out of memory -- stop execution before any exception mechanism runs. register_shutdown_function runs regardless, and error_get_last tells you whether a fatal error ended the script.
<?php
declare(strict_types=1);
register_shutdown_function(function (): void {
$err = error_get_last();
if ($err !== null && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR], true)) {
echo "shutdown caught fatal: {$err['message']}\n";
} else {
echo "clean shutdown\n";
}
});
echo "work starting\n";
echo "work done\n";
Output:
work starting
work done
clean shutdown
The shutdown function is registered, then the script does its work and ends normally, so error_get_last returns no fatal error and the handler reports a clean shutdown. Had a fatal error occurred, the same handler would still run -- it is the only hook that fires after a fatal error -- and error_get_last would report the fatal message, letting you log it and show a graceful page instead of a blank white screen.
Error reporting levels
error_reporting is a bitmask deciding which severities are active. Development wants everything visible; production typically silences low-value noise like notices and deprecations while keeping warnings and errors. The levels combine with bitwise operators.
<?php
declare(strict_types=1);
function willReport(int $level, int $severity): bool {
return (bool) ($level & $severity);
}
$prod = E_ALL & ~E_NOTICE & ~E_DEPRECATED;
echo 'reports E_WARNING? ', willReport($prod, E_WARNING) ? 'yes' : 'no', "\n";
echo 'reports E_NOTICE? ', willReport($prod, E_NOTICE) ? 'yes' : 'no', "\n";
$dev = E_ALL;
echo 'dev reports E_NOTICE? ', willReport($dev, E_NOTICE) ? 'yes' : 'no', "\n";
echo 'dev reports E_DEPRECATED? ', willReport($dev, E_DEPRECATED) ? 'yes' : 'no', "\n";
Output:
reports E_WARNING? yes
reports E_NOTICE? no
dev reports E_NOTICE? yes
dev reports E_DEPRECATED? yes
The production mask E_ALL & ~E_NOTICE & ~E_DEPRECATED clears the notice and deprecation bits, so willReport returns yes for a warning but no for a notice. The development mask E_ALL keeps every bit set, reporting notices and deprecations too. This is exactly how error_reporting gates which errors reach your handler: set E_ALL in development to catch everything early, and a trimmed mask in production paired with display_errors = Off and log_errors = On so real problems are logged without leaking or drowning in noise.
Real World Example: A Central Error Reporter
Production applications route every failure through one reporter that logs the full detail server-side and returns a safe status and message for the client. Mapping exception types to HTTP statuses in one place keeps the policy consistent and the leak-prevention reliable.
<?php
declare(strict_types=1);
final class NotFoundException extends RuntimeException {}
final class ErrorReporter {
private array $log = [];
public function handle(\Throwable $e): array {
$this->log[] = get_class($e) . ': ' . $e->getMessage();
[$status, $userMsg] = match (true) {
$e instanceof NotFoundException => [404, 'Not found'],
$e instanceof InvalidArgumentException => [400, 'Bad request'],
default => [500, 'Server error'],
};
return ['status' => $status, 'message' => $userMsg];
}
public function logCount(): int { return count($this->log); }
public function lastLog(): string { return end($this->log) ?: ''; }
}
$reporter = new ErrorReporter();
foreach ([new NotFoundException('user 9'), new InvalidArgumentException('bad id'), new RuntimeException('disk full')] as $e) {
$r = $reporter->handle($e);
echo $r['status'], ' ', $r['message'], "\n";
}
echo 'logged entries: ', $reporter->logCount(), "\n";
echo 'last log: ', $reporter->lastLog(), "\n";
Output:
404 Not found
400 Bad request
500 Server error
logged entries: 3
last log: RuntimeException: disk full
Every exception is logged with its class and message before anything else, so the server retains full detail. A match (true) maps known types to a status and a safe user message: NotFoundException to 404, InvalidArgumentException to 400, and anything else to a generic 500. The three failures produce clean, non-leaking responses, and the log holds all three entries -- the last being the raw "disk full" that the user never saw. Wiring this reporter into set_exception_handler gives the whole application one consistent failure policy.
The design flaw is that the log here is an in-memory array, which means every logged detail is lost the instant the request ends -- exactly when you most need it. In PHP's shared-nothing model each request starts with a fresh process state, so an in-memory log cannot survive to be read later; the "disk full" entry that the user was correctly shielded from is also invisible to the operator, because nothing persisted it. This recreates the very failure the reporter was built to prevent: the detail exists just long enough to be discarded. A real reporter must write to something durable -- a log file via error_log, a syslog socket, or a monitoring service -- synchronously enough that a crash later in the request cannot swallow it. There is a deeper subtlety too: logging itself can fail (the disk is full, after all), so the logging path must degrade gracefully rather than throw from inside the error handler, which would mask the original error entirely. An error reporter that can lose its own reports, or crash while reporting, is worse than none, because it creates false confidence that failures are being recorded when they are silently evaporating. The mature pattern separates the two concerns entirely: a thin, always-succeeding transport (append to a file descriptor, hand off to syslog) that cannot itself throw, wrapped so that any failure in the transport degrades to the most minimal possible fallback rather than propagating -- because the one place you can never afford an unhandled exception is the code whose job is to handle exceptions.
Common Mistakes
- Displaying errors to users in production.
display_errors = Onleaks stack traces, paths, and queries to attackers. Turn it off in production and log instead.
- Suppressing errors entirely. Silencing everything with
@or a no-op handler hides failures. Log them; do not make them disappear.
- No global exception handler. Without
set_exception_handler, an uncaught exception prints a raw trace. Install one to guarantee a safe, logged response.
- Ignoring fatal errors.
try/catchcannot catch a fatal error. Useregister_shutdown_functionwitherror_get_lastto handle them gracefully.
- Logging to memory or nowhere durable. An in-memory log dies with the request. Write to a file, syslog, or a monitoring service so detail survives.
- Letting the logger throw. If logging itself fails and throws inside the handler, the original error is masked. Make the logging path fail safe.
- One audience for all messages. Showing the same detail to users and operators either leaks internals or starves debugging. Split the safe message from the logged detail.
- Not converting warnings to exceptions. Leaving notices and warnings as loose output lets bugs slip by. A
set_error_handlerthat throwsErrorExceptionsurfaces them.
- Inconsistent status mapping. Deciding statuses ad hoc across the codebase yields incoherent responses. Map exception types to statuses in one central place.
Best Practices
- Turn
display_errorsoff in production and log errors instead, so users never see raw traces.
- Install
set_exception_handleras the last-resort catch-all, logging full detail and returning one safe message.
- Register a shutdown function that inspects
error_get_lastto handle fatal errors the exception system cannot catch.
- Convert built-in warnings and notices into
ErrorExceptionwithset_error_handler, so they are handled like any exception.
- Log to something durable -- a file, syslog, or a monitoring service -- never to per-request memory that vanishes.
- Make the logging path itself fail safe, so a failure while logging never masks the original error.
- Split the two audiences: a generic message for users, full context for the log an engineer reads.
- Centralise the mapping of exception types to statuses and messages, keeping failure responses consistent across the app.
Practice Exercises
- Install a
set_error_handlerthat throwsErrorException, then trigger an undefined-array-key warning inside atryand catch it as an exception.
- Register a
set_exception_handlerthat prints a logged line and a generic user line, then throw an uncaught exception and observe the handler run.
- Register a shutdown function that reports whether
error_get_lastindicates a fatal error, and show it reporting a clean shutdown for a normally-ending script.
- Build a central
ErrorReporterthat maps exception types to statuses, logs each failure, and returns a safe message, then change its log target from an array toerror_logand explain why durability matters.