PHP error guide

set_exception_handler misses Throwable types: meaning and fix

Error summary

Register a valid callable whose parameter accepts Throwable, log safely, and avoid throwing another exception from the handler.

What it means

Register a valid callable whose parameter accepts Throwable, log safely, and avoid throwing another exception from the handler.

What the error means

The global exception handler is invalid or typed too narrowly; on PHP 7+ it can receive any uncaught Throwable, including Error.

Why PHP produces it

set_exception_handler validates its callback, and the runtime later passes the uncaught Throwable to that callback at the final application boundary.

PHP version notes

The behavior described for set_exception_handler misses Throwable types applies to PHP 7.4–8.4 unless a narrower version is stated; exact wording can vary by SAPI and patch release.

Most common causes

  • The named function is not loaded before registration.
  • The handler parameter is declared as Exception instead of Throwable.
  • The handler itself accesses unavailable services and throws again.

Minimal examples

BAD — reproduces the problem

php
set_exception_handler(function (Exception $e) { echo $e; });

FIXED — safer pattern

php
set_exception_handler(static function (Throwable $e): void { error_log((string)$e); http_response_code(500); });

Step-by-step diagnosis

  1. Verify is_callable() immediately before registration.
  2. Reflect the callback parameter and ensure it accepts Throwable.
  3. Exercise the handler with both a RuntimeException and a TypeError in a non-production test.

Fixes

Register a robust final handler

Accept Throwable, write to a dependable logger, and send a generic response.

php
set_exception_handler(static function (Throwable $e): void {
    error_log((string) $e);
    http_response_code(500);
});

Common mistakes when fixing it

  • Printing sensitive traces to users.
  • Expecting execution to continue after the handler returns.
  • Depending on a complex container that may be broken.

How to prevent it

  • Register the handler during deterministic bootstrap.
  • Keep its logging path simple and tested.
  • Accept Throwable on supported modern PHP versions.

Web server / environment notes

cli, fpm, apache. The callback runs only for uncaught throwables and does not resume execution.

Tags: cli,fpm,apache

Categories