PHP Error Handling

PHP Error Handling

In PHP, it is very easy to handle the default error. An error message that contains filename, line number and a message describes that the error is sent to the browser. Error handling becomes an important part when we are creating any scripts and web applications.

There are different php error handling methods which are described below:

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

Error Handling Using “die()” Statements

Let us take an example,

PHP Error Handling

You will get the following error if the file does not exists:

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

To prevent the above error, do code as following:

Error Handling

Now, if the file does not exit, then it will display an error message as “File not found”.

Create a Custom Error Handler

In order to create a custom handler, we need to create a function that we can call at the time when an error occurs in PHP.

Syntax:

error_function(error_level,error_message,error_file,error_line,error_context)

where;

error_level: It specifies the error report level for the user-defined error.

error_message: It specifies the error message for the user-defined error.

error_file: It specifies the filename in which the error occurred.

error_line: It specifies the line number in which the error occurred.

error_context: It specifies an array containing every variable, and their values, in use when the error occurred.

Error Report levels

Error report levels are the user-defined error handler can be used for:

  • E_WARNING
  • E_NOTICE
  • E_USER_ERROR
  • E_USER_WARNING
  • E_USER_NOTICE
  • E_RECOVERABLE_ERROR
  • E_ALL

To handle errors, create a function:

Handle Error

Above code represent a simple error handling function. Now, the error level and an error message will be displayed when it is triggered. After creation of the error handling function, its the time to decide when it should be triggered.

Set Error Handler

In PHP, there is a default error handler that is already built in PHP.

Syntax

set_error_handler(“customErrorHandler”);

Let us take an example,

Set Error Handler Example

Now, it will give an output as below:

Error: [8] Undefined variable: test

Trigger an Error

n PHP, it can be done by the trigger_error() function.

Let us take an example,

Trigger Error Example

Above code will give an output as below:

Notice: Value should be 3 or below
in C:\myfolder\test.php on line 6