LPU Live Error Handling
LPU Live Error Handling
• Error reporting
Basic Error Handling: Using the die() function
• These functions can be used to stop script
execution if a critical error occurs e.g.
<?php
$file=fopen("mytestfile.txt","r");
?>
• But it will give an error,,,,if the file is not
present
Use Die function to prevent it
<?php
if(file_exists("mytestfile.txt")) {
$file = fopen("mytestfile.txt", "r");
} else {
die("Error: The file does not exist.");
}
?>
Custom Error Handler
• PHP allows you to define custom error-handling
functions using set_error_handler().
• error_function(error_level,error_message,
error_file,error_line,error_context)
Now lets create a function to handle errors:
function customError($errno, $errstr) {
echo "Error [$errno]: $errstr<br>";
}
set_error_handler("customError");
// Trigger an error
echo $undefined_var; // Will call customError
Testing the error handler by trying to output
variable that does not exist:
• <?php
set_error_handler("customError");
//trigger error
echo($test);
?>
Trigger an Error