Exception driven programming
von Gaylord, am 9 Juni 2009 - 0 Kommentare
With Exceptions being my favourite add-on in PHP 5, i loved this post.
Error handling is something that often is regarded as something that is somehow needed but a simple bailout often appears to do it. The more complex your application gets, the more important it becomes to do the right error handling and logging.
This goes into both directions: excessive error logging results in spending too much money on hard disks and hides the real problems between gigabytes of "user uploaded file with name collsion" messages. Therefore it is important to define a robust, consistent error handling and logging ruleset at the beginning of the development cycle. Adding error handling while coding is quite simple, doing it afterwards is a nightmare. And debugging an application with non-adequate error handling and logging is a real pain.
In my world, errors are in general reported with exceptions, of course. But only if they are of interest for the surrounding application of course, not if they are handled locally. So i wrap all system calls and php calls that return "false" in case of error in classes and let them evaluate the error response and throw an exception.
For handling these exceptions, we have some rules where i come from:
1. Let exceptions fall. Dont catch them if you cant handle them. Never ever catch an exception and throw another one just to cast them. You'll loose the stack trace and any additional information. (in PHP 5.3 we will hopefully be able to cast an exception by throwing another one that is constructed from the original exception)
2. Define a common Exception Log method that produces a standard output of your exception including stack trace and extra data.
3. Dont log errors when the Exception is thrown, but log them on the top-level if nobody has catched them. This way you prevent log output for catched exception.
4. Give exceptions a code. Define a catalogue of all exception codes in a common place. This way you can handle a group of exceptions that same way but still know the individual differences
5. Define a last defense line where all exceptions are caught so under no circumstances a user ever gets to see one. Instead, catch all exceptions there and output something like "Come back later". For responses to Ajax calls, transcode the exceptions to a JSON repsonse (see 6.)
And then: Excpetion driven development comes in. Whenever you have an error that was a hell to find, make sure to improve the error handling around it so it becomes as you would have needed if before. Do this before fixing the actual bug, so you can test the error output.
I did this a lot in our current 270,000 LOC application and it made it more easy to debug every time.