0
0
PhpHow-ToBeginner · 3 min read

How to Use set_error_handler in PHP: Simple Guide

Use set_error_handler in PHP to define a custom function that handles errors instead of the default error handler. Pass your error handling function's name to set_error_handler, which will then receive error details when an error occurs.
📐

Syntax

The set_error_handler function sets a user-defined function to handle errors. It takes one required parameter: the name of your custom error handler function. This function should accept specific parameters to receive error details.

  • error_handler: The callback function name that handles errors.
php
set_error_handler(callable $error_handler): callable|false
💻

Example

This example shows how to create a custom error handler that prints error details and then triggers a warning to demonstrate it.

php
<?php
function myErrorHandler(int $errno, string $errstr, string $errfile, int $errline): bool {
    echo "Custom error: [$errno] $errstr in $errfile on line $errline\n";
    return true; // Prevents PHP internal error handler from running
}

set_error_handler('myErrorHandler');

// Trigger an error to test the handler
trigger_error('Test warning', E_USER_WARNING);
?>
Output
Custom error: [512] Test warning in /path/to/script.php on line 11
⚠️

Common Pitfalls

  • Not returning true from your error handler will cause PHP's default error handler to run as well.
  • Using set_error_handler does not catch fatal errors like parse errors.
  • Make sure your error handler function has the correct parameters: errno, errstr, errfile, errline, and optionally errcontext (deprecated).
  • Do not forget to restore the original error handler with restore_error_handler() if needed.
php
<?php
// Wrong: Missing parameters in handler
function wrongHandler() {
    echo "Error caught";
}

// Right: Correct parameters
function rightHandler(int $errno, string $errstr, string $errfile, int $errline): bool {
    echo "Handled error: $errstr\n";
    return true;
}

set_error_handler('rightHandler');
trigger_error('Test error');
?>
Output
Handled error: Test error
📊

Quick Reference

Remember these key points when using set_error_handler:

  • Define a function with parameters: errno, errstr, errfile, errline.
  • Return true to stop PHP's default error handler.
  • Use restore_error_handler() to revert to the default handler.
  • It handles warnings, notices, and user-generated errors, but not fatal errors.

Key Takeaways

Use set_error_handler to define a custom function that handles PHP errors.
Your error handler function must accept error details as parameters and return true to prevent default handling.
set_error_handler does not catch fatal errors like parse errors.
Always restore the original error handler if you temporarily override it.
Test your error handler by triggering errors like warnings or notices.