What are the best practices for implementing global error handling in PHP scripts, especially when dealing with exceptions?
When implementing global error handling in PHP scripts, especially when dealing with exceptions, it is important to set up a custom error handler and exception handler. This allows you to catch and handle any errors or exceptions that occur throughout your script, providing a centralized way to manage errors and log them appropriately.
// Custom error handler function
function errorHandler($errno, $errstr, $errfile, $errline) {
// Log or handle the error as needed
error_log("Error: $errstr in $errfile on line $errline");
}
// Set custom error handler
set_error_handler("errorHandler");
// Custom exception handler function
function exceptionHandler($exception) {
// Log or handle the exception as needed
error_log("Exception: " . $exception->getMessage() . " in " . $exception->getFile() . " on line " . $exception->getLine());
}
// Set custom exception handler
set_exception_handler("exceptionHandler");
// Example code that may throw an exception
try {
// Code that may throw an exception
throw new Exception("An example exception");
} catch (Exception $e) {
// Exception will be caught by the custom exception handler
}