Handle PHP errors and exceptions

This post describes how to handle PHP errors and exceptions.


Handle PHP errors

Predefined constants


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.


// 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

// Doesn't display any error

Customize PHP errors handling

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


// 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>';

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.


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

Leave a Reply

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