2082 8

BIT301 ยท 2082 ยท 5 marks

What is the error handler? Write a program to demonstrate error handler function.

What is the error handler? Write a program to demonstrate error handler function. [5]

Web Technology IIChapter 10: Sessions, Cookies, and Error HandlingError handling and error handlers

Quick answer

An error handler is a user-defined function that is called automatically whenever a PHP error occurs. Instead of displaying the default PHP error messages, a custom error handler allows the programmer to control how errors are handled, such as logging them, displaying custom messages, or redirecting the user.

Error Handler in PHP

Definition

In PHP, the built-in function set_error_handler() is used to register a custom error handling function.


Syntax

set_error_handler("functionName");

The custom error handler function must accept the following parameters:

ParameterDescription
$errnoError number/level
$errstrError message
$errfileFile where error occurred
$errlineLine number where error occurred

Program to Demonstrate Error Handler

<?php

// Step 1: Define the custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>Custom Error Handler Triggered!</b> ";
    echo "Error Number : " . $errno . " ";
    echo "Error Message: " . $errstr . " ";
    echo "Error File   : " . $errfile . " ";
    echo "Error Line   : " . $errline . " ";
    echo "<hr>";
}

// Step 2: Register the custom error handler
set_error_handler("myErrorHandler");

// Step 3: Trigger errors to test the handler

// Triggering a user-defined notice
trigger_error("This is a user notice!", E_USER_NOTICE);

// Triggering a user-defined warning
trigger_error("This is a user warning!", E_USER_WARNING);

// Triggering a division by zero warning
$a = 10;
$b = 0;
if ($b == 0) {
    trigger_error("Division by zero is not allowed!", E_USER_ERROR);
}

echo "Program continues after error handling.";

?>

Output

Custom Error Handler Triggered!
Error Number : 1024
Error Message: This is a user notice!
Error File   : /path/to/file.php
Error Line   : 20
---
Custom Error Handler Triggered!
Error Number : 512
Error Message: This is a user warning!
Error File   : /path/to/file.php
Error Line   : 23
---
Custom Error Handler Triggered!
Error Number : 256
Error Message: Division by zero is not allowed!
Error File   : /path/to/file.php
Error Line   : 28

Key Points

  • set_error_handler() overrides PHP's default error handling.
  • trigger_error() is used to manually generate an error for testing.
  • Common error constants: E_USER_NOTICE, E_USER_WARNING, E_USER_ERROR.
  • Custom error handlers help in debugging, logging, and providing user-friendly error messages.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.