Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

How do you handle Unhandled Exceptions and Fatal Errors gracefully in PHP 8 with custom error handlers?

Real-World Scenario / Incident Description

Ensuring any unhandled fatal exception renders a clean JSON payload to API clients and reports stack traces to Sentry without printing raw PHP traces.

111 views • Updated 1 month ago

Handling \Throwable (Exception + Error)

In PHP 7+, all exceptions and fatal runtime errors implement \Throwable:

set_exception_handler(function (\Throwable $e) {
    Log::error($e->getMessage(), ['trace' => $e->getTraceAsString()]);

    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'error' => 'Internal Server Error',
        'code' => 500,
    ]);
    exit;
});
Related Concepts: #Error Handling #Exceptions #Throwable #Sentry