Tutorial

PHP Error Handling

PHP has set of functions which can deal with the handling the errors generated during the program execution. As a good programming practice it is good to use the Error Handling function which let developer to handle the error in any way they want.

I generally log my error in database using Custom Error Handler Function. So let’s see how you can handle PHP Errors using custom handler.

PHP has good flexibility for error logging using the function [code]set_error_handler()[/code] function. All you have to do is to create one function and set that function as you error handler function.

This error handler function can accept five parameter. Have a look at below code:

[cc lang=”php”]

function my_custom_err_handler($number, $string, $file, $line, $context)
{
// Write your code here
// to manage the error occured,
// Comman practice is to store in
// .txt file, store in DB, mail to own.
}

[/cc]

Parameter Explanation

$number: This is the integar number which defines the Error Reporting Level.
$string: This string contains the error description.
$file: This defines the file in which error occured. This is optional parameter.
$line: This defines the line number on which error occured. This is optional parameter.
$context: This one is the last and optional parameter. This will contain an array of every variable that existed in the scope the error was triggered in.

So now you have a function ready which have code to handle your errors. But we have to inform PHP about existence of this function to handle the errors. In that case we have to set the Error Handler Function using [code]set_error_handler()[/code] function.

Set Custom Error Handler

[cc lang=”php”]
set_error_handler(“my_custom_err_handler”);
[/cc]

What to Write in Error Handler Function?

Main use of Error Handler Function is to log the errors which occured during the program execution. We can log these errors in various ways including logging to .txt, .xml file, storing in database, you can also code to send the mail upon error. Its totally depends on the requirements.

Shares:

Leave a Reply

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