PHP Error Handling

  • Avinash
  • 0
  • Oct 26, 2011
  • Tutorial

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 set_error_handler() 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:

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. }
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.
}

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 set_error_handler() function.

Set Custom Error Handler

set_error_handler("my_custom_err_handler");
  set_error_handler("my_custom_err_handler");

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.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: