Hello,
I hope this is the right forum for this topic. I thought I’d ask for some suggestions on how to handle errors in PHP.
Ideally, I’d like ALL PHP errors to be thrown as exceptions.
At the very first, I’d like the ability to handle isolated errors. For example, take the following code example:
$query = $DB->query($sql);
Say it queries a table that doesn’t exist and produces the following:
MySQL ERROR:
Error Number: 1146
Description: Table 'foo.exp_bar' doesn't exist.
How do I handle these errors?
I’ve tried using set_error_handler, ob_start, and error_reporting all with no success.
Any help would be much appreciated.
Thanks, Mike
I’m a little fuzzy- are you talking about outputting to the user an error message? And frontend/backend?
A final plugin/module shouldn’t throw a php/mysql error at all when done. I leave errors set to show for superadmins in ‘Admin- System Prefs- Output and debug’ on always. The server is set to show all errors, and as soon as one crops up, I get it fixed.
Guess I’m confused- are you talking about having the server show errors (and it’s currently not, so it’s hard to debug) or are you talking custom user messages when users try to do something they shouldn’t, etc?
Hi Robin,
Thanks for the reply.
I’m just talking about error handling in my plugin/module/extension (or any other PHP script for that matter). For example, let’s assume that the following line in my script throws an error:
$query = $DB->query("SELECT * from my_non_existing_table");
Currently that message would cause the script to die and the message would be displayed to the superadmin. However, I’d like that statement to throw an exception rather than an error so that I can put that statement into a try/catch block and handle the problem within the script.
Thanks, Mike
P.S. Congrats on the new position!
Hm- yes, test out my new CM brain ability.
For a plugin, you’d really want to ensure it’s not going to throw a mysql error at the outset rather than after the fact. Though it may be the specific example that’s making me balk. For that specific case, you’d want to validate values that will be used in the queries via PHP, and if there’s still the possibility of the table not existing, see “check” queries in MySQL, which should yield the answer without erroring out. (Or you could look at CI- Derek mentioned they have a table_exists() function- you might look at that for some inspiration.)
Make some sense? The EE approach would be to make sure the mysql error doesn’t occur in the first place, rather than try to catch the error after the fact via exceptions or something along those lines.
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.