Building A Generic Error Reporting Class In PHP (
Page 1 of 9 )
The traditional method of building dynamic, PHP-based Web sites - mixing HTML
elements with PHP code - can result in mangled Web pages (and much user angst)
if errors take place during script execution. But yes, you can avoid the ugliness
- plug in our handy error reporting class, which provides a simple way of trapping
script errors and generating consistent, user-friendly error screens.One of the most fundamental tasks during the development cycle for a software
application involves writing code to trap and gracefully recover from exceptions.
This might seem pretty obvious, but the reality - as anyone who's ever spent
time developing a robust Web application will tell you - is completely different.
Most developers, especially those new to the Web paradigm, treat error handling
like an unwanted stepchild, preferring instead to concentrate their efforts on
implementing and delivering the application against aggressive deadlines. Error
handling is usually an after-thought...if it's thought of at all.
This is a shame, because most programming languages - including PHP, which is
the subject of this article - come with a full-featured error handling API, which
provides you with a number of options when it comes to trapping and resolving
errors. Making use of such an error-handling API in a consistent manner throughout
the scripts that power your application bears rich dividends: your code is more
robust, application test time is shorter (since most errors have been thought
through and handled in your code), and users never get the opportunity to see
ugly, incomprehensible debug messages generated from the language's internals.
Even if you develop and release a Web application without building in any error-handling
routines (either through ignorance or laziness), you can be sure that your customer's
going to demand a fix for it in the next release of the software. And since it's
one of the few things you're likely to do over and over again when building Web
applications, it's worthwhile spending a little time to make the process as painless
as possible.
That's where this article comes in. Over the next few pages, I'll be attempting
to build a reusable library of functions that allow you to handle script errors
in a generic manner, in an attempt to save myself (and, hopefully, you) some time
when the next project comes around. The end result of this experiment will be
a PHP class that can be easily included in your scripts, and that provides a simple
way to trap and display errors consistently. I should warn you at the outset that
it may not - in fact, probably will not - meet *all* your needs; however, the
process should be instructive, especially if you're new to object programming
in PHP, and you'll have very little difficulty customizing it to your own requirements.
Let's get going!