Handle PHP errors and exceptions

This post describes how to handle PHP errors and exceptions.

Prerequisites

Handle PHP errors

Predefined constants

E_ERROR (1), E_WARNING (2), E_PARSE (4), E_NOTICE (8), E_CORE_ERROR (16), E_CORE_WARNING (32), E_COMPILE_ERROR (64), E_COMPILE_WARNING (128), E_USER_ERROR (256), E_USER_WARNING (512), E_USER_NOTICE (1024), E_STRICT (2048), E_RECOVERABLE_ERROR (4096), E_DEPRECATED (8192), E_USER_DEPRECATED (16384), E_ALL (32767).

More information on http://php.net/manual/en/errorfunc.constants.php

Display PHP errors

The ini_set function enables the display of PHP errors.

ini_set('display_errors', 'On');

Set the PHP errors reporting level

The error_reporting function allows to choose which PHP errors to display.

Examples:

// Display E_ERROR, E_PARSE and E_USER_ERROR errors
error_reporting(E_ERROR | E_PARSE | E_USER_ERROR);

// Display all errors except E_WARNING et E_NOTICE
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);

// Display all errors
error_reporting(E_ALL);

// Doesn't display any error
error_reporting(0);

Customize PHP errors handling

The set_error_handler function allows to choose the function that handles PHP errors.

set_error_handler('HandleError');

// Display all errors except E_WARNING et E_NOTICE
function HandleError($Number, $Message, $File, $Line) {
    $ExceptionsArray = array(E_WARNING, E_NOTICE);
    if (!in_array($Number, $ExceptionsArray)) {
        $Message = '<b>Error</b>: '.$Message.' in <b>'.$File.'</b> on line <b>'.$Line.'</b>';
        exit($Message);
    }
}

The use of the set_error_handler function cancels the errors reporting level defined with the error_reporting function.

E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING and E_STRICT errors are not handled by the function passed as the set_error_handler parameter.

Generate a PHP error

The trigger_error function allows to generate a custom error.

trigger_error('This is a E_USER_WARNING error', E_USER_WARNING);

Handle PHP exceptions

The set_exception_handler function allows to choose the function that handles PHP exceptions.

set_exception_handler('HandleError');

// Display exceptions
function HandleException($Exception) {
    $Message = '<b>Exception</b>: '.$Exception->getMessage().' in <b>'.$Exception->getFile().'</b> on line <b>'.$Exception->getLine().'</b>';
    exit($Message);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*