How to handle those pesky errors in PHP
(Page 4 out of 4)Creating your own errors
Triggering your own errors sounds pretty simple, especially with functions like trigger_error which I've already talked about a bit, but it's actually harder than you think. The whole point of triggering your own errors is so that the rest of your PHP application knows what's going on. This sounds a bit cryptic, so let me demonstrate it with an example:
// I want to load a file, so I use a custom function:
$data = load_file ('C:\my\file.txt');
// What happened? Did I successfully load the file or not?
// How can I found out?
function load_file ($file) {
// Check if file exists
if (file_exists($file) == false) {
// Need to return an error, but how?
}
// Load the file...
}
?>
The above example demonstrates exactly what I mean. I use a custom function to load a file, and I expect it to return file data, but it's possible that an error occurs, which needs to be handled by my script. The most common solution is to simply have the function return false, like so:
// I want to load a file, so I use a custom function:
$data = load_file ('C:\my\file.txt');
if ($data == false) {
echo 'Unable to load file';
}
function load_file ($file) {
// Check if file exists
if (file_exists($file) == false) {
return false;
}
// Load the file...
}
?>
This does the job, and works, but it's far from perfect because you don't really know what the problem is, and therefore can't return an informative error message either.
Another possibility is to use exceptions, like so:
// I want to load a file, so I use a custom function:
try {
$data = load_file ('C:\my\file.txt');
} catch (Exception $e) {
echo 'Error ' . $e->getCode() . ': ' . $e->getMessage();
}
function load_file ($file) {
// Check if file exists
if (file_exists($file) == false) {
throw new Exception('File doesn\'t exist', 10);
return false;
}
// Load the file...
}
?>
This is already much better, because you can define your own error numbers and messages, which means you can create informative messages, and handle each error differently. But if you're still stuck on PHP4, this is no solution, because you can't use exceptions, and another disadvantage of using exceptions is that you must catch them, otherwise they will halt execution of your script.
A better solution is to use a global static class which emulates exceptions in a different way, and this is a method I really like myself. See the (simplified) example below to understand what I mean:
// I want to load a file, so I use a custom function:
$data = load_file ('C:\my\file.txt');
// Anything went wrong? Check error class for code and message
if ($data == false) {
echo 'Error ' . Error::getCode() . ': ' . Error::getMessage();
}
function load_file ($file) {
// Check if file exists
if (file_exists($file) == false) {
Error::throwError ('File doesn\'t exist', 10);
return false;
}
// Load the file...
}
Class Error {
function throwError ($msg, $num=0) {
$errors =& Error::errors();
$errors[] = array('errmsg' => $msg, 'errnum' => $num);
}
function getCode() {
// Get code of latest error
$errors =& Error::errors();
$latest = end($errors);
return $latest['errnum'];
}
function getMessage() {
// Get message of latest error
$errors =& Error::errors();
$latest = end($errors);
return $latest['errmsg'];
}
function &errors() {
static $errors;
return $errors;
}
}
?>
In the example above you get the best of both worlds: exception-like functionality, meaning it's possible to define your own error codes and messages, it's PHP4 compatible, and there's no need to use a try-catch block either, because it doesn't matter if you don't catch any of these errors. Another advantage is that it's possible to get a list of all the errors that happened in your script.
Of course the above is just a simplified example, and there are different ways of doing it, but I've had much success with the above method.
Conclusion
In this article I've first taken you through the basics of error handling in PHP, and after that shown you some more advanced PHP5 features, ending with a custom solution for triggering your own errors. Errors can be a really useful tool, especially during development but also on your live production website. Make sure you log every error that happens, including notices, and check your error log every 2-3 days. It's likely you'll spot something you haven't seen before, and it could save you a lot of trouble in the long run.
If you have any comments or questions on this article, feel free to leave them in the comments below or join us at the PHPit Forums.
April 11th, 2006 at 8:08 am
help
can anyone teach me how to disable the refresh button because that is the cause of my errors
hehhehehe
thanks Master Programmers
July 26th, 2006 at 4:40 pm
Hi I would like to use your error code but i am having problems with defining the directory the line from the tutorial is: define (’logfile’, dirname(__FILE__) . ‘/logfile.txt’);
I have changed this to: define (’logfile’, C:/log/logfile.txt(__FILE__) . ‘/logfile.txt’);
It throws up a parse error, I am a newbie so any help would be appreciated.