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.
set_exception_handler() catches uncaught exceptions globally. Use it to log errors and show a friendly error page before the script terminates.
<?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"]);
}
});
Always log the full stack trace in your exception handler — the message alone is rarely enough to diagnose the problem.