PHP set_error_handler() - Set Custom Error Handler
Welcome to this comprehensive tutorial on the PHP set_error_handler() function. In this guide, we will explore how to implement custom error handling in PHP by setting a user-defined function to handle runtime errors effectively. Whether you want to log errors differently, show user-friendly messages, or take special actions on errors, understanding set_error_handler() is essential.
Prerequisites
- Basic understanding of PHP syntax and error handling mechanisms
- Familiarity with PHP's built-in error types and error_reporting()
- PHP environment set up for testing (PHP 5.0+ recommended)
What is PHP set_error_handler()?
The set_error_handler() function in PHP allows you to specify a custom callback function that will be invoked whenever a PHP runtime error occurs. This enables developers to override default PHP error handling and implement tailored logic, such as logging to custom files, sending alert emails, or displaying custom messages.
Function Signature
set_error_handler(callable $error_handler, int $error_types = E_ALL): ?callable
Parameters:
$error_handler: The user-defined callback function to handle errors. It must accept specific parameters.$error_types(optional): Bitmask of error types this handler should process (default isE_ALL).
Returns: The previous error handler or null on failure.
How to Use set_error_handler() - Step-by-Step Setup
- Define your custom error handler function. This function should accept these parameters:
int $errno- the error levelstring $errstr- the error messagestring $errfile- filename where the error occurredint $errline- line number of the errorarray $errcontext(deprecated in PHP 7.2+) - an array of variables in the scope.
- Call
set_error_handler()passing your function name or callable. - Generate an error to see your handler in action.
- Restore original error handler (optional).
Practical Example: Custom Error Logging
<?php
// Step 1: Define the custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline) {
$errorTypes = [
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_NOTICE => 'Notice',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
];
$type = isset($errorTypes[$errno]) ? $errorTypes[$errno] : 'Unknown Error';
$message = "[" . date('Y-m-d H:i:s') . "] [$type] $errstr in $errfile on line $errline\n";
// Log error message to a file
error_log($message, 3, __DIR__ . '/custom_errors.log');
// Optionally display user-friendly message
if ($errno === E_USER_ERROR) {
echo "A serious error occurred. Please contact support.";
exit(1);
}
// Don't execute PHP internal error handler
return true;
}
// Step 2: Set the custom error handler
set_error_handler('myErrorHandler');
// Step 3: Trigger an error
echo $undeclaredVariable; // Notice: undefined variable
// Trigger a user-defined error
trigger_error("Custom user error", E_USER_ERROR);
?>
In this example:
myErrorHandler()processes various types of errors.- Errors are logged into
custom_errors.logwith timestamp and error type. - For critical user errors, output a notice and stop execution.
- The handler returns
true, preventing PHP's internal error handler from also running.
Best Practices for Using set_error_handler()
- Always return
truein your error handler to bypass PHP’s default error reporting if completely handling errors. - Use error_reporting() and
$error_typesparameter to control which errors trigger your handler. - Log errors securely and avoid revealing sensitive details to end users.
- Keep your error handler performance-efficient to avoid slowing the application.
- Remember
set_error_handler()does not catch fatal errors (E_ERROR) and exceptions; useset_exception_handler()or register shutdown functions for those.
Common Mistakes When Using set_error_handler()
- Ignoring error handler parameters: Your callback must accept the correct number and type of parameters.
- Not returning
trueorfalseproperly: Returningfalsehands off error handling back to PHP causing duplicate messages. - Using deprecated
$errcontextin recent PHP versions: Avoid or handle gracefully to maintain compatibility. - Expecting it to handle fatal errors: Fatal errors are not handled by this function.
- Not resetting the error handler if needed: Use
restore_error_handler()to revert to PHP's default handler.
Interview Questions
Junior Level Questions
- Q1: What does the
set_error_handler()function do?
A1: It sets a custom user-defined function to handle PHP runtime errors. - Q2: What kind of callback function signature must be used with
set_error_handler()?
A2: The callback should accept at least$errno, $errstr, $errfile, $errlineparameters. - Q3: Can
set_error_handler()handle all types of PHP errors?
A3: No, it cannot handle fatal errors likeE_ERRORor parse errors. - Q4: How do you restore PHP's default error handling after setting a custom handler?
A4: Use therestore_error_handler()function. - Q5: Which parameter of
set_error_handler()limits the types of errors caught?
A5: The optional second parameter$error_types.
Mid Level Questions
- Q1: What happens if your custom error handler returns
false?
A1: PHP’s internal error handler is invoked in addition to the custom handler. - Q2: How can you log errors inside your custom error handler?
A2: Use PHP functions likeerror_log()inside the handler to write errors to files or monitoring systems. - Q3: Why should you avoid exposing raw error messages to users in production?
A3: Because error details may contain sensitive info, posing security risks. - Q4: Is it possible to handle exceptions with
set_error_handler()?
A4: No, exceptions are handled separately usingset_exception_handler(). - Q5: How does the second parameter
$error_typeswork withset_error_handler()?
A5: It specifies a bitmask to filter which error levels the handler processes, such asE_WARNING | E_NOTICE.
Senior Level Questions
- Q1: How can you ensure graceful shutdown handling of fatal errors along with a custom
set_error_handler()?
A1: Useregister_shutdown_function()to catch fatal errors and combine withset_error_handler()for recoverable errors. - Q2: Describe a strategy to categorize and prioritize errors inside a custom error handler.
A2: Map error numbers to severity levels, log critical errors immediately, warn for minor ones, and notify admins for certain conditions. - Q3: What are potential performance implications of a poorly implemented
set_error_handler()?
A3: Excessive logging, complex processing, or blocking operations in the handler can slow down the application and increase overhead. - Q4: How can you integrate
set_error_handler()with modern PHP frameworks' error handling pipelines?
A4: Register the handler early in the bootstrap process, and delegate error processing to framework components or PSR-3 compliant loggers. - Q5: Explain why capturing the
$errcontextparameter is discouraged in recent PHP versions.
A5: It was deprecated due to security risks and performance overhead, as it captures all variables in scope, potentially leaking sensitive data.
Frequently Asked Questions (FAQ)
- Can
set_error_handler()handle parse errors (syntax errors)? - No, parse errors occur before runtime, so
set_error_handler()cannot catch them. - What is the difference between
set_error_handler()andset_exception_handler()? set_error_handler()handles PHP runtime errors, whileset_exception_handler()handles uncaught exceptions.- Is it possible to have multiple error handlers simultaneously?
- No, only one global custom error handler can be set at a time. You can chain handlers manually within a custom function.
- Does
set_error_handler()affect error reporting settings? - It works alongside error_reporting(), and respects the active error levels configured when deciding to invoke your handler.
- How do I disable the built-in PHP error messages completely?
- Return
truefrom your handler to prevent PHP's default error handler from running, and setdisplay_errorsoff in php.ini to hide errors.
Conclusion
Using set_error_handler() empowers PHP developers to create robust, customizable error handling strategies. By defining your own logic for responding to various error types, you improve maintainability, user experience, and system monitoring. Follow best practices, handle parameters carefully, and complement set_error_handler() with shutdown handlers and exception management for full coverage of PHP application error handling.