2079 6

BIT301 ยท 2079 ยท 5 marks

What is error handler? Write a PHP program to show use of error handler to format and print errors.

What is error handler? Write a PHP program to show use of error handler to format and print errors. [5]

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

Quick answer

An error handler is a function of your own that PHP calls whenever it raises a diagnostic, in place of printing its built in message. Instead of a raw grey line of text in the middle of a page, the handler receives the details as arguments and can format them, write them to a log, show a friendly message, or stop the script. It is registered with set_error_handler().

Error handler in PHP

set_error_handler("functionName");

The handler is called with four useful arguments:

ParameterDescription
$errnoThe error level, one of the E_* constants
$errstrThe message text
$errfileThe file in which the error was raised
$errlineThe line number in that file

What it returns matters. Returning true tells PHP the error has been dealt with, so its own handler stays quiet; returning false lets the standard handler run as well, which is how you keep normal logging while adding your own formatting.

A custom handler covers the diagnostics the engine raises, that is E_WARNING, E_NOTICE, E_DEPRECATED and the E_USER_* family. It is never invoked for E_ERROR, E_PARSE or the core and compile level errors, and it is not invoked for a thrown Exception or Error; those need try and catch, and a fatal fault needs register_shutdown_function() with error_get_last().

A program that formats and prints errors

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    $labels = [
        E_WARNING     => "Warning",
        E_NOTICE      => "Notice",
        E_DEPRECATED  => "Deprecated",
        E_USER_ERROR  => "User error",
        E_USER_WARNING=> "User warning",
        E_USER_NOTICE => "User notice",
    ];
    $label = $labels[$errno] ?? "Unknown";

    echo "<div style='border:2px solid #c00; padding:10px; background:#ffe6e6;'>";
    echo "<strong>" . $label . " caught</strong> ";
    echo "<b>Level:</b> " . (int) $errno . " ";
    echo "<b>Message:</b> " . htmlspecialchars($errstr, ENT_QUOTES, "UTF-8") . " ";
    echo "<b>File:</b> " . htmlspecialchars(basename($errfile), ENT_QUOTES, "UTF-8") . " ";
    echo "<b>Line:</b> " . (int) $errline . " ";
    echo "</div> ";

    if ($errno === E_USER_ERROR) {
        exit(1);   // PHP does not halt by itself once a handler is installed
    }
    return true;
}

set_error_handler("myErrorHandler");

echo $undefinedVariable;            // PHP 8: E_WARNING, value 2

include "nonexistent_file.php";     // E_WARNING, the file cannot be opened

trigger_error("This is a custom user error.", E_USER_ERROR);   // 256

The message text is passed through htmlspecialchars() before it is printed, and the numbers are cast to int, because an error string often quotes a value the visitor supplied and echoing it raw into a page would be a cross site scripting hole. Only the file's base name is shown, so the server's directory layout is not published.

What the page shows

+-----------------------------------------------------------+
| Warning caught                                            |
| Level: 2                                                  |
| Message: Undefined variable $undefinedVariable            |
| File: error_demo.php                                      |
| Line: 30                                                  |
+-----------------------------------------------------------+

+-----------------------------------------------------------+
| Warning caught                                            |
| Level: 2                                                  |
| Message: include(nonexistent_file.php): Failed to open    |
|          stream: No such file or directory                |
| File: error_demo.php                                      |
| Line: 32                                                  |
+-----------------------------------------------------------+

+-----------------------------------------------------------+
| User error caught                                         |
| Level: 256                                                |
| Message: This is a custom user error.                     |
| File: error_demo.php                                      |
| Line: 34                                                  |
+-----------------------------------------------------------+

Points worth noting

Reading an undefined variable is an E_WARNING with the value 2 in PHP 8, not the E_NOTICE with the value 8 that PHP 5 and 7 produced, and the message now names the variable, as in "Undefined variable $undefinedVariable". A missing array key changed in the same way. A failed include raises two warnings, one from the failed open and one from the failed inclusion, so the handler fires twice for that single line.

trigger_error() raises a diagnostic on purpose and is the usual way to test a handler. Once a custom handler is installed, PHP no longer stops the script on E_USER_ERROR, so the handler must call exit() itself if the run should end, which is why the example does so.

A custom handler improves readability, keeps file paths and query fragments off a production page, and gives one place to add error_log(), so the same code can present a tidy message to the visitor and a complete record to the developer.

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