codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐘

PHP

39 / 56 topics
37Error Handling in PHP38Try Catch Blocks39Custom Error Handlers
Tutorials/PHP/Custom Error Handlers
🐘PHP

Custom Error Handlers

Updated 2026-05-15
10 min read

Custom Error Handlers

Introduction

In PHP, error handling is a crucial aspect of building robust and reliable applications. By default, PHP provides several mechanisms to handle errors, such as the built-in error_reporting function and the use of exception handling with try-catch blocks. However, sometimes you may want more control over how errors are reported or handled in your application.

Custom error handlers allow you to define your own functions that will be called when an error occurs, giving you the flexibility to log errors, display custom error messages, or even perform other actions like sending notifications. In this tutorial, we'll explore how to create and use custom error handlers in PHP.

Concept

PHP provides two main ways to handle errors: using error handling functions and exception handling. While exceptions are great for handling recoverable runtime errors, sometimes you need a more general approach to error management. This is where custom error handlers come into play.

A custom error handler is a user-defined function that can be set up to catch all types of PHP errors. You can use the set_error_handler() function to register your custom error handler. This function takes two parameters: the name of the callback function and an optional bitmask specifying which error levels should be handled by this handler.

Here's a basic example of how to create and use a custom error handler:

Examples

Basic Custom Error Handler

Let's start with a simple example where we define a custom error handler that logs errors to a file.

<?php

// Define the custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    // Log the error details to a file
    $logFile = 'error.log';
    $errorMessage = "[$errno] $errstr - Error on line $errline in $errfile\n";
    
    if (!file_put_contents($logFile, $errorMessage, FILE_APPEND)) {
        echo "Failed to write to log file.";
    } else {
        return true; // Return true to indicate that we've handled the error
    }
}

// Set our custom error handler
set_error_handler('myErrorHandler');

// Trigger an error for demonstration purposes
echo $undefinedVariable;

In this example, we define a function myErrorHandler that takes four parameters: $errno, $errstr, $errfile, and $errline. These represent the error number, error message, file where the error occurred, and line number, respectively. Inside the function, we log these details to a file named error.log.

We then use set_error_handler() to register our custom error handler. When an error occurs (like trying to echo an undefined variable), our custom handler is invoked, and the error details are logged.

Custom Error Handler with HTML Output

Sometimes you might want to display errors in a more user-friendly way, such as embedding them into your HTML output. Here's how you can modify the previous example to do that:

<?php

// Define the custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    // Display an error message in HTML format
    echo "<div style='color: red;'>Error [$errno]: $errstr - Error on line $errline in $errfile</div>";
    
    return true; // Return true to indicate that we've handled the error
}

// Set our custom error handler
set_error_handler('myErrorHandler');

// Trigger an error for demonstration purposes
echo $undefinedVariable;

In this version, instead of logging the error to a file, we display it directly in HTML with a red color. This can be useful for debugging during development or providing feedback to users.

Restoring Default Error Handler

If you need to temporarily disable your custom error handler and use PHP's default error handling, you can restore it using restore_error_handler():

<?php

// Define the custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    // Display an error message in HTML format
    echo "<div style='color: red;'>Error [$errno]: $errstr - Error on line $errline in $errfile</div>";
    
    return true; // Return true to indicate that we've handled the error
}

// Set our custom error handler
set_error_handler('myErrorHandler');

// Trigger an error for demonstration purposes
echo $undefinedVariable;

// Restore the default error handler
restore_error_handler();

// Now, any new errors will be handled by PHP's default mechanism
trigger_error("This is a test error.", E_USER_NOTICE);

In this example, after setting our custom error handler and triggering an error, we call restore_error_handler() to revert to PHP's default error handling. Any subsequent errors will be handled according to the default settings.

What's Next?

Now that you've learned how to create and use custom error handlers in PHP, you might want to explore more advanced topics such as logging errors to external systems like databases or monitoring tools, or implementing more sophisticated error reporting mechanisms. Additionally, understanding security best practices in PHP is crucial for building secure applications.

In the next section, we'll dive into "Security in PHP," where we'll discuss common security vulnerabilities and how to mitigate them in your PHP applications.


PreviousTry Catch BlocksNext Security in PHP

Recommended Gear

Try Catch BlocksSecurity in PHP