SyntaxStudy
Sign Up
PHP Global Exception Handler
PHP Intermediate 5 min read

Global Exception Handler

Global Exception Handler

set_exception_handler() catches uncaught exceptions globally. Use it to log errors and show a friendly error page before the script terminates.

Example
<?php
set_exception_handler(function (Throwable $e) {
    error_log(sprintf(
        "[%s] %s in %s:%d
%s",
        date("Y-m-d H:i:s"),
        $e->getMessage(),
        $e->getFile(),
        $e->getLine(),
        $e->getTraceAsString()
    ));

    if (php_sapi_name() === "cli") {
        fwrite(STDERR, $e->getMessage() . "
");
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Internal Server Error"]);
    }
});
Pro Tip

Always log the full stack trace in your exception handler — the message alone is rarely enough to diagnose the problem.