A central error and exception handler in PHP

Advanced  Nov 3, 2026

Catch every error in one place, log it, and show a safe page to visitors.

A central error and exception handler in PHP
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

One file for all errors

<?php
// bootstrap.php
const DEBUG = false;

set_error_handler(function (int $no, string $msg, string $file, int $line): bool {
    if (!(error_reporting() & $no)) {
        return false;                         // respect the @ operator
    }
    throw new ErrorException($msg, 0, $no, $file, $line);
});

set_exception_handler(function (Throwable $e): void {
    $line = date('c') . ' ' . get_class($e) . ': ' . $e->getMessage()
          . ' in ' . $e->getFile() . ':' . $e->getLine() . "\n";
    error_log($line, 3, __DIR__ . '/logs/app.log');

    http_response_code(500);
    echo DEBUG ? '<pre>' . htmlspecialchars((string)$e) . '</pre>' : 'Something went wrong. Please try again later.';
});

register_shutdown_function(function (): void {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        error_log(date('c') . ' FATAL ' . $err['message'] . ' ' . $err['file'] . ':' . $err['line'] . "\n", 3, __DIR__ . '/logs/app.log');
    }
});
How the code in this section fits into the page.
How the code in this section fits into the page.

Why it helps

  • Warnings become exceptions, so problems are not ignored silently.
  • Visitors never see file paths or SQL.
  • You still get the details in the log.
The main points of this section.
The main points of this section.

Remember

  • Keep the logs folder private and rotate old logs.
  • Do not log passwords, tokens or card numbers.
  • Show a reference code to the visitor and write the same code in the log, so support can find the exact error.
The main points of this section.
The main points of this section.

More tutorials