PHP › Error & Exception Handling

How do you set a global exception handler and error handler in PHP to consistently catch and log any uncaught exceptions or errors across an entire application?

Advanced

Answer

PHP provides set_exception_handler and set_error_handler functions that let you register custom functions to be called automatically whenever an uncaught exception occurs or a PHP error is triggered anywhere in your application, providing a centralized place to consistently log these issues, notify a monitoring service, and display a generic, user friendly error page, rather than relying on every single piece of code to individually handle every possible error condition.
set_exception_handler(function (Throwable $e) {
    error_log($e->getMessage());
    http_response_code(500);
    echo 'Something went wrong';
});
Real-world example A production application registers a global exception handler that automatically logs every uncaught exception to a monitoring service and displays a generic error page to the user, ensuring no unhandled error ever exposes sensitive internal details or a raw stack trace to an end user.

Common follow-ups: How do modern frameworks like Laravel and Symfony implement this kind of centralized exception handling?;What is the difference between set_exception_handler and set_error_handler?