Explain about error handling in php ?

  • Error handling is the process of catching errors elevated from program and then taking correct action. If you would handle errors then the most common error checking methods given in PHP.
    • die() function
    • Custom errors and error triggers
    • Error reporting

die() function

  • To write the PHP program you should check all possible error condition before checking and take appropriate action when required.
  • The following example without having /tmp/test.xt file and with this file.
<?php
if(!file_exists("/tmp/test.txt")) {
die("File not found");
}else {
$file = fopen("/tmp/test.txt","r");
print "Opend file sucessfully";
}
// Test of the code here.
?>

Custom errors and error triggers

  • We can write own function to handling any error. PHP provides a framework to define error handling function.
  • This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context)

Syntax

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

Error reporting

  • These error report levels are the different types of error the user-defined error handler can be used.
  • The errors are .E_ERROR, E_WARNING, E_PARSE, E_NOTICE, E_CORE_ERROR, E_CORE_WARNING, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_STRICT, E_RECOVERABLE_ERROR, E_ALL
  • These all errors handle to using set_error_handler function.
<?php
error_reporting( E_ERROR );

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

die();
}

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

//trigger error
myFunction();
?>

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,