Skip to content
PHP Logo

How can custom error handlers in PHP be used to handle exceptions and errors more effectively?

Custom error handlers in PHP can be used to handle exceptions and errors more effectively by allowing developers to define their own error handling logic. This can help in centralizing error handling code, making it easier to manage and maintain. By customizing error handlers, developers can also log errors, display user-friendly error messages, and gracefully handle exceptions.

php
// Define custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    // Log the error
    error_log("Error: $errstr in $errfile on line $errline");
    
    // Display user-friendly error message
    echo "An error occurred. Please try again later.";
}

// Set custom error handler
set_error_handler("customErrorHandler");

// Trigger a custom error
trigger_error("This is a custom error message", E_USER_ERROR);