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?
AdvancedAnswer
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.