PHP Error Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. Error handling is an important part of web application development. A good web application must have the capabilities to handle error gracefully. There are two different error handling methods :

  • die() statement
  • Custom errors and error triggers

die() Statement :

The die() statement prints a message and exits the current script. It is used to print the alternate message instead of showing error. The die() statement is only used to print string messages. Now lets see an example of error handling with die() statement :
<?php

  $file = "doc.txt";
  if(file_exists($file)) {
    $myfile = fopen($file, "w");
  } else {
    die("Error : File does not found on the server.");
  }

?>
Output :

Error : File does not found on the server.

The above php script tries to open the file name "doc.txt" and if the file does not found on the server then it calls the die() function, which display the message and exits the execution of the script. This function is an alias of the exit() function.


Custom errors and error triggers :

PHP provides a framework to define our own function for error handling. Creating a custom error handler is quite simple, we just need to create a special function that can be called when an error occurs.

The custom error function must be able to handle a minimum of two parameters error_level and error_message, but it can accept up to five parameters. (optional parameters : error_file, error_line, error_context). The syntax of error function is as follow  is :

With two parameters :
 error_function(error_level, error_message);
With optional parameters :
 error_function(error_level, error_message, error_file, error_line, error_context);
The Parameters are :
  • error_level : The error_level parameter is required. It specifies the error report level for the user-defined error and must be a value number.
  • error_message : The error_message parameter is required. It specifies the error message for the user-defined error.
  • error_file : The error_file parameter is optional. It specifies the filename in which the error occurred.
  • error_line : The error_line parameter is optional. It specifies the line number in which the error occurred.
  • error_context : The error_context parameter is optional. It specifies an array containing every variable, and their values, in use when the error occurred.

Possible Error Levels in PHP :

Constant Value Description
E_ERROR 1 Fatal run-time errors. Execution of the script is halted.
E_WARNING 2 Non-fatal run-time errors. Execution of the script is not halted.
E_PARSE 4 Compile-time parse errors. Parse errors should only be generated by the parser.
E_NOTICE 8 Run-time notices. The script found something that might be an error, but could also happen when running a script normally.
E_CORE_ERROR 16 Fatal errors that occur during PHP's initial start-up.
E_CORE_WARNING 32 Non-fatal run-time errors. This occurs during PHP's initial start-up.
E_USER_ERROR 256 Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error().
E_USER_WARNING 512 Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error().
E_USER_NOTICE 1024 User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error().
E_STRICT 2048 Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.
E_RECOVERABLE_ERROR 4096 Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()).
E_ALL 8191 All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0).


Now here is the steps to setup custom error function :

1. Setting up Error_Level :

The above error levels can be set by using the error_reporting()  PHP build-in library function. The syntax is :
 error_reporting ( [int $level] )
Example :
 error_reporting (E_ERROR)

2. Defining Custom error function :

The syntax of Defining custom error function is :
 error_function(error_level, error_message)
Example :
<?php

  function handleError( $errno, $errstr ) {
    echo "<b>Error:</b> [$errno] -- $errstr";
    echo "<br />";
    echo "Terminating PHP Script";
    die();
  }

?>

3. Assign Custom error function :

Syntax :
 set_error_handler("Error_Function_Name")
Example :
 set_error_handler("handleError")
Now lets see an example :
<?php

  error_reporting( E_ERROR );

  function handleError($errno, $errstr) {
    echo "<b>Error</b> [$errno] :- $errstr<br/>";
    echo "Terminating PHP Script ....";
    die();
  }

  // set up error handler
  set_error_handler("handleError");

  // below lines trigger error
  $file = "doc.txt";
  $handle = fopen($file, "r");

?>
Output :

Error [2] :- fopen(doc.txt): failed to open stream: No such file or directory
Terminating PHP Script ....


Next Topic :