Throwing Custom Errors?
In a recent article on PHPit I talked a bit on throwing your own errors, and what the best methods are, and I'm interested in what others think.
I use a lot of different (custom) libraries and components in my PHP scripts, and figuring out the best way to return errors is always a problem. The easiest way is to simply return false when something bad happens like so:
$data = load_file ('C:\my\file.txt');
if ($data == false) {
echo 'Something bad happened';
}
function load_file ($file) {
if (file_exists($file) == false) {
return false;
}
// Load file data
}
?>
But this has several limitations, and provides no flexiblity at all. Another possibility is to use exceptions, like so:
try {
$data = load_file ('C:\my\file.txt');
} catch (Exception $e) {
echo $e->getMessage;
}
function load_file ($file) {
if (file_exists($file) == false) {
throw new Exception('File can\'t be found');
}
// Load file data
}
?>
But this only works if you're using PHP5 (and my web host doesn't support it yet) and you must catch the exception, otherwise a really ugly fatal error is printed. So that's not really a perfect solution either.
If you're library is built around a class, then something like this would be possible:
$lib = New MyLib;
$data = $lib->load_file ('C:\my\file.txt');
if ($data == false) {
echo $lib->error;
}
Class MyLib {
var $error;
function load_file ($file) {
if (file_exists($file) == false) {
$this->error = 'File can\'t be found';
return false;
}
// Load file data
}
}
?>
This seems like the best solution to me, although it does have a few small drawbacks. For example, when using the load_file() function again, you have to clear any previous errors, or else errors could get mixed up.
In the article I also present another solution involving a static class, which is used as a global error stack, and it sort-of emulates exceptions. But that approach doesn't really work if you're using individual libraries.
So, any thoughts on this? Have I missed any solutions, which might work much better?
April 20th, 2006 at 1:24 pm
Although I don’t think you have intended your blog post to teach people basic OOP PHP, it certianly thought me the basics. I was studying your code for some time, rewritting it to make it do different things.
That’s a great blog post. I also like it how you use return false / true in that way, it’s great.
I do however, do one thing. I make functions which handle my errors at the moment. For example, I have a list of error shortcut refference names in database, and call them by there shortcut reference name, and display the full error message that way. By doing it via the database, I can easily update the error using a PHP form any time I want, as you already know.
I do like your method though, since it thought me basic OOP PHP.
Thank you for your blog post, reZo.