PHP Error Handling- Creating a Custom Error Handler

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

Creating a Custom Error Handler

A Custom Error Handler is a special function which is called when an error occurs in PHP.

This function should accept at least two parameters, ie error level and error message and at the max it may accept up to five parameters ie file, line-number, and the error context:

Syntax

    error_function(error_level,error_message,
    error_file,error_line,error_context)
    Parameter Description
    error_level Required. Specifies the error report level for the user-defined error. Must be a value number.
    error_message Required. Specifies the error message for the user-defined error
    error_file Optional. Specifies the filename in which the error occurred
    error_line Optional. Specifies the line number in which the error occurred
    error_context Optional. Specifies an array containing every variable, and their values, in use when the error occurred

Error Report levels

These error report levels are the different types of error the user-defined error handler can be used for:

    Value Constant Description
    2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
    8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
    256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
    512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
    1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
    4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
    8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

Now lets create a function to handle errors:

    function customError($erroeNo, $errorString)
    {echo “<b>Error:</b> [$errorNo] $errorString<br />”;
    die();
    }

The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.

Here we have created an error handling function, so mow we we need to decide when it should be triggered.

Set Error Handler

PHP provides a built in default error handler error handler.

You can also change the error handler to apply for only some errors, so this way you can make more handlers for different type of errors, which will handle the errors in specific ways.

    set_error_handler(“customError”);

Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.

In this example below we are testing the error handler by trying to output variable that does not exist:

    For eg:

    <?php //error handler function
    function customError($errorNo, $errorString)
    {
    echo “<b>Error:</b> [$errorNo] $errorString”;
    }
    //set error handler
    set_error_handler(“customError”);
    //trigger error
    echo($num);
    ?>

    Output:

    Error: [8] Undefined variable: num

Trigger an Error

In the above example we triggered the error without any reason. We need some valid trigger for the error handler to be triggered. When a user inputs data, some wrong input may be provided so we need to trigger the handler whenever a user inputs a invalid data. In PHP, this is done by the trigger_error() function.

In this example an error occurs if the “num” variable is less than “1″:

    For eg:

    <?php
    $num=0;
    if ($num<1)
    {
    trigger_error(“Number must be greater than 0″);
    }
    ?>

    Output:

    Notice: Number must be greater than 0 in C:\applications\errorTest.php on line 6

By this method you can trigger an error anywhere you wish in a script. By adding a second parameter, you can specify what error level is triggered.

Possible error types:

  • E_USER_ERROR – Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
  • E_USER_WARNING – Non-fatal user-generated run-time warning. Execution of the script is not halted
  • E_USER_NOTICE – Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally

In this example an E_USER_WARNING occurs if the “num” variable is less than “1″. If an E_USER_WARNING occurs we will use our custom error handler and end the script:

    For eg:

    <?php //error handler function
    function customError($errorNo, $errorString)
    {
    echo “<b>Error:</b> [$errorNo] $errorString<br />”;
    die();
    }
    //set error handler
    set_error_handler(“customError”,E_USER_WARNING);
    //trigger error
    $num=0;
    if ($test<1)
    {
    trigger_error(“Number must be greater than 1″,E_USER_WARNING);
    }
    ?>

    Output:
    Error: [512] Value must be 1 or below

PHP Error Handling- die() Statement

Posted by tutor | Posted in PHP Tutorial | Posted on 16-12-2009-05-2008

0

PHP provides a default error handling, which is very simple. An error message is sent to the browser, with filename, line number and a message describing the error.

Error handling is a vital part while working with scripts and creating web applications.

Error checking and handling helps you handle the errors your way, ie you can do what you want to do in case an error occurs. It makes your code look more professional and also provides security.

This tutorial contains some of the most common error checking methods in PHP.

Some of the most common error checking methods of PHP are:

  • Simple “die()” statements
  • Custom errors and error triggers
  • Error reporting

Using the die() function

The first example shows a simple script that opens a text file:

    <?php
    $file=fopen(“welcome.txt”,”r”);
    ?>
    Error Output if the file does not exist:

    Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:No such file or directory in C:\webfolder\test.php on line 2

You can avoid this situation by simple methods. First look for the file if it exists, then open it and if not then you can use the die() function.

    <?php
    if(!file_exists(“welcome.txt”))
    {
    die(“File not found”);
    }
    else
    {
    $file=fopen(“welcome.txt”,”r”);
    }
    ?>
    Error Output if the file does not exist:

    File not found

The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.