In PHP development, fatal errors can cause the script to stop running abruptly. These errors may be due to syntax issues, logic mistakes, or resource exhaustion. To ensure application stability, it's essential to properly manage and handle these fatal errors.
PHP provides the set_error_handler() function, which allows developers to define custom error handling logic. This function can intercept and manage different types of errors, including fatal ones.
// Set up a custom error handler
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
// Handle the error here
});
The custom error handler function receives four parameters that provide detailed information about the error:
You can detect fatal errors by comparing the error code to the E_ERROR constant. Once identified, you can log the error, send notifications, and safely terminate the script.
if ($errno === E_ERROR) {
// Handle fatal error
}
The example below demonstrates how to capture and handle a fatal error using a custom function. It includes error logging, admin notifications, and a controlled script shutdown.
// Set up a fatal error handler
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
if ($errno === E_ERROR) {
// Log the error
error_log("Fatal Error: $errstr in $errfile on line $errline");
// Send admin notification
mail('admin@example.com', 'Fatal Error Alert', "Error Details: $errstr");
// Exit the script safely
exit;
}
});
// Simulate a fatal error
trigger_error('Simulated fatal error', E_USER_ERROR);
Implementing a custom PHP error handling mechanism ensures your application responds gracefully to fatal errors. From logging and notifications to recovery measures, proper error handling significantly improves the robustness and reliability of your PHP projects.