Intermediate LevelPHP 8+
How do you register a global exception fallback handler using set_exception_handler() to render clean error pages?
❓ Interview Prompt: Explain set_exception_handler(), global uncaught exception handling, logging uncaught exceptions, and returning 500 JSON responses.
If an exception is thrown and not caught by any local 'try/catch' block, PHP terminates the script and emits an "Uncaught Exception" error.
Global Exception Handler ('set_exception_handler()'):
Registers a fallback callback to handle any uncaught exceptions globally:
1
Log exception details and stack traces securely to disk/Datadog.
2
Clear output buffers.
3
Emit a clean HTTP 500 response page or JSON error payload to the user without exposing sensitive code traces.
Code Implementation Example
php
<?php
// Register global uncaught exception fallback handler
set_exception_handler(function (Throwable $e): void {
// 1. Log full exception stack trace to secure server log
error_log("[UNCAUGHT EXCEPTION] " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
// 2. Send clean 500 response payload to client
http_response_code(500);
echo json_encode(['error' => 'Internal Server Error', 'code' => 500]);
exit();
});💡Registering a global uncaught exception handler to return clean HTTP 500 responses.
🎯 Interview Key Takeaway
Use set_exception_handler() to catch unhandled exceptions globally, log stack traces, and render clean HTTP 500 responses.
#set_exception_handler#Exceptions#Global Handler#Intermediate
Back to all PHP 8+ Questions→