Error Handlers and Error Reporting

5.Error Handlers and Error Reporting

M

In this chapter

We'll learn how error_reporting decides which messages PHP reports, how display_errors and log_errors decide where they go, how set_error_handler() turns warnings into ErrorException, why the @ operator is a trap, how set_exception_handler() catches whatever nobody else did, and how a shutdown function notices the fatal errors that can't be caught.

17–19 min

The Problem in Real Life

Marcus lists what BookBay's code does today when something fails. A warning from a missing file: shown on screen in development, ignored in production, and the code carries on with false. An uncaught exception: a white page. A memory-limit failure: a white page. In all three cases, the production log is empty unless someone remembered log_errors.

"We're not going to fix this one if at a time," he says. "PHP lets us decide, once, for the whole project, what happens to every kind of problem."

M

Three handlers and three settings — and nothing can fail without us knowing.

Marcus

Default PHP Behaviour vs. Handlers You Control

Settings decide

error_reporting, display_errors and log_errors decide which messages exist and where they go.

Warnings become exceptions

An error handler can throw ErrorException, so a missing file can't be silently ignored.

A last line of defence

An exception handler and a shutdown function catch what everything else missed.

Error Handlers and Error Reporting

Project-wide rules for failure: chapters 1–4 handled problems where they happened. This chapter sets the rules for the whole project — the code that runs once, at the start of every request. It covers:

  • error_reporting: which levels of message are reported.
  • display_errors and log_errors: where reported messages go.
  • set_error_handler(): your own code for warnings and notices.
  • The @ operator: why silencing is a trap.
  • set_exception_handler() and shutdown functions: the last resort.

error_reporting: the setting error_reporting (in php.ini, or the function error_reporting() at runtime) is a filter: only messages whose level is in it are reported at all. Its value is a combination of the level constants from chapter 4, like E_ALL & ~E_DEPRECATED ("everything except deprecations"). Use E_ALL everywhere — development and production. Hiding deprecations or notices in production doesn't make them go away; it only means you hear about them when PHP upgrades and they become errors. What changes between environments is where messages go, not which ones exist.

error_reporting values
<?php
echo E_ALL, "\n"; // 30719: every level
echo E_ALL & ~E_DEPRECATED, "\n"; // everything except deprecations
error_reporting(E_ALL); // the right choice everywhere
var_dump((bool) (error_reporting() & E_WARNING)); // is E_WARNING reported?
// 30719
// 22527
// bool(true)

display_errors and log_errors: a reported message can be shown in the output and/or written to a log. display_errors shows it in the page or terminal — useful on your laptop, dangerous in production, where it can reveal file paths, SQL and data to anyone (Act 01). log_errors writes it to the log, to the file named by error_log, or to the web server's log or stderr when that's empty. Production: display_errors = Off, log_errors = On. That's exactly the combination BookBay's server was missing — it had both Off, so the error went nowhere. The diagram below shows the path every message takes.

The path of a warning

file_get_contents() raises E_WARNING

"Failed to open stream"

1. filter

Is E_WARNING in error_reporting?

no → nothing happens at all

2. handler

Error handler set?

yes → your function decides (often: throw ErrorException)

3. otherwise PHP's own handling

display_errors = On

printed in the page (development)

log_errors = On

written to the error_log (always)

php.ini: development and production
; development (your laptop)
error_reporting = E_ALL
display_errors = On
log_errors = On
; production (the server)
error_reporting = E_ALL
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php/bookbay-errors.log

set_error_handler(): PHP lets you replace its handling of warnings, notices and deprecations with your own function: set_error_handler(function (int $severity, string $message, string $file, int $line): bool { ... }). The classic use, done by Laravel and Symfony too, is to throw an exception from it: an ErrorException. A missing file then stops the code like any exception, can be caught, and can't be silently ignored. Two details matter. First, start with if (!(error_reporting() & $severity)) { return false; }, so messages filtered out by error_reporting (and by @, below) stay quiet. Second, an error handler only sees the non-fatal levels; E_ERROR, E_PARSE and other fatal errors never reach it. restore_error_handler() goes back to the previous handler.

Turning warnings into ErrorException
<?php
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
if (!(error_reporting() & $severity)) {
return false; // filtered out (or silenced with @): let PHP decide
}
throw new ErrorException($message, 0, $severity, $file, $line);
});
try {
$json = file_get_contents('/srv/bookbay/holidays.json');
} catch (ErrorException $e) {
echo "Caught: ", $e->getMessage(), " (severity ", $e->getSeverity(), ")\n";
}
// Caught: file_get_contents(/srv/bookbay/holidays.json): Failed to open stream: No such file or directory (severity 2)

The @ operator: writing @ before an expression — @file_get_contents($path) — silences its warnings. It looks convenient, and it's a trap: the reason for the failure disappears, and the code still has to deal with false. With an error handler installed, the handler is still called, but error_reporting() returns a smaller value inside it (4437 since PHP 8), which is why the check above matters. Prefer checking first (is_file($path)) or catching the ErrorException. In PHP 8, @ no longer hides fatal errors at all.

set_exception_handler(): a function registered with set_exception_handler() is called with any exception nobody caught, instead of PHP's "Uncaught …" fatal error. It's the last resort for exceptions: log the full exception with its chain, send a 500 status, and show a friendly page. After it runs, the script ends — there's no going back to where the exception was thrown. Register it once, in the project's front script, before anything else. (The PHP Playground ignores exception handlers, so this example runs on your own computer; the output below is real.)

The last-resort exception handler (run on your computer)
<?php
set_exception_handler(function (Throwable $e): void {
http_response_code(500);
error_log("[error] " . get_class($e) . ": " . $e->getMessage()
. " in " . basename($e->getFile()) . ":" . $e->getLine());
echo "Sorry, something went wrong. We've been notified.\n";
});
echo "Loading booking...\n";
throw new RuntimeException("Booking 4812 does not exist");
echo "never printed\n";
// $ php booking.php
// Loading booking...
// [error] RuntimeException: Booking 4812 does not exist in booking.php:11
// Sorry, something went wrong. We've been notified.

Shutdown functions for real fatal errors: memory and time limits (chapter 4) bypass both handlers. But functions registered with register_shutdown_function() still run when the script ends, for any reason, and error_get_last() returns the last error as an array with type, message, file and line. If its type is fatal (E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR), the shutdown function can log it and print the friendly page. With all three registered, nothing can fail unnoticed. PHP 8.5 also adds get_error_handler() and get_exception_handler(), so code can check which handlers are active. The table below sums up who handles what.

Table — Who handles what
Problemtry/catchset_error_handler()set_exception_handler()Shutdown function
Warning, notice, deprecationOnly if the handler throwsYesNoSees it in error_get_last()
Exception or Error, caughtYesNoNoNo
Exception or Error, uncaughtNoNoYesRuns afterwards
Fatal: memory, time limit, syntaxNoNoNoYes
A shutdown function notices a fatal error (run on your computer)
<?php
register_shutdown_function(function (): void {
$error = error_get_last();
if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
error_log("[critical] " . $error['message'] . " in " . basename($error['file']) . ":" . $error['line']);
echo "Sorry, something went wrong. We've been notified.\n";
}
});
ini_set('memory_limit', '4M');
$rows = [];
while (true) {
$rows[] = str_repeat('x', 1000);
}
// $ php report.php
// Fatal error: Allowed memory size of 4194304 bytes exhausted (tried to allocate 20480 bytes) in report.php on line 14
// [critical] Allowed memory size of 4194304 bytes exhausted (tried to allocate 20480 bytes) in report.php:14
// Sorry, something went wrong. We've been notified.

trigger_error() for your own messages: your code can raise classic messages too, with the E_USER_ levels: trigger_error("formatPrice() with a float is deprecated, pass pence", E_USER_DEPRECATED) warns other developers that something will change, without breaking anything today. It goes through error_reporting, the error handler and the log, like PHP's own deprecations. For real failures, throw an exception instead.

trigger_error() for your own deprecation
<?php
function formatPrice(int|float $amount): string
{
if (is_float($amount)) {
trigger_error("formatPrice() with a float is deprecated, pass pence", E_USER_DEPRECATED);
$amount = (int) round($amount * 100);
}
return "£" . number_format($amount / 100, 2);
}
echo formatPrice(27.5), "\n";
// Deprecated: formatPrice() with a float is deprecated, pass pence in main.php on line 6
// £27.50

Key Takeaway

error_reporting filters which messages are reported — use E_ALL in every environment; display_errors (dev only) and log_errors (always On) decide where they go. set_error_handler() receives non-fatal messages and usually throws ErrorException so warnings can't be ignored; check error_reporting() & $severity first to respect filtering and @. Avoid @: it hides the reason, not the failure. set_exception_handler() is the last resort for uncaught exceptions — log, send 500, show a friendly page, then the script ends. register_shutdown_function() with error_get_last() catches truly fatal errors. Use trigger_error() with E_USER_DEPRECATED for your own deprecations.

Why This Matters

Every framework does exactly this at startup: Laravel's bootstrap registers an error handler that throws ErrorException, an exception handler that renders error pages, and a shutdown function for fatals. Now you know what that code is for.

These settings are the difference between a production incident you hear about in a minute and one a customer reports a week later. They're also part of every server checklist in Act 25.

BookBay's front script now registers all three handlers, error_reporting is E_ALL, and the server logs everything. The log fills up fast — with lines like "RuntimeException: Booking 4812 does not exist in booking.php:11", and nothing else. Which request was it? Which customer? Was the database up? And the friendly page says the same thing for a missing booking as for a crashed server. That's the next chapter: logging and production error handling.