0
0
PHPprogramming~5 mins

Set_error_handler function in PHP

Choose your learning style9 modes available
Introduction

The set_error_handler function lets you control what happens when an error occurs in your PHP program. Instead of showing the default error message, you can create your own way to handle errors.

You want to log errors to a file instead of showing them on the screen.
You want to show friendly messages to users when something goes wrong.
You want to stop the program from crashing and handle errors smoothly.
You want to customize how different types of errors are treated.
You want to debug your program by catching errors in a special way.
Syntax
PHP
set_error_handler(callable $error_handler, int $error_levels = E_ALL): ?callable

The $error_handler is a function you create that will run when an error happens.

The optional $error_levels lets you choose which errors to catch (default is all errors).

Examples
This example sets a simple error handler that prints error details.
PHP
<?php
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Error [$errno]: $errstr in $errfile on line $errline\n";
}
set_error_handler('myErrorHandler');
This example uses an anonymous function to handle errors with a short message.
PHP
<?php
set_error_handler(function($errno, $errstr) {
    echo "Custom error: $errstr\n";
});
This example sets the handler only for warnings and notices, ignoring other errors.
PHP
<?php
set_error_handler('myErrorHandler', E_WARNING | E_NOTICE);
Sample Program

This program sets a custom error handler that prints a friendly message when an error happens. Then it causes two errors: dividing by zero and using an undefined variable. Instead of default errors, the custom messages show.

PHP
<?php
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Oops! Error number $errno happened: $errstr on line $errline in file $errfile\n";
}

set_error_handler('customErrorHandler');

// This will cause a warning (division by zero)
echo 10 / 0;

// This will cause a notice (undefined variable)
echo $undefinedVar;
OutputSuccess
Important Notes

The error handler function must accept at least four parameters: error number, error message, file name, and line number.

After setting a custom error handler, PHP will use it for errors matching the specified levels.

Remember to restore the original error handler if needed using restore_error_handler().

Summary

set_error_handler lets you catch and handle errors your way.

You create a function that runs when an error happens.

This helps make your program friendlier and easier to debug.