Error handling in PHP

One thing to add to what was said already is that it’s paramount that you record any errors in your web application into a log. This way, as Jeff “Coding Horror” Atwood suggests, you’ll know when your users are experiencing trouble with your app (instead of “asking them what’s wrong”).

To do this, I recommend the following type of infrastructure:

  • Create a “crash” table in your database and a set of wrapper classes for reporting errors. I’d recommend setting categories for the crashes (“blocking”, “security”, “PHP error/warning” (vs exception), etc).
  • In all of your error handling code, make sure to record the error. Doing this consistently depends on how well you built the API (above step) – it should be trivial to record crashes if done right.

Extra credit: sometimes, your crashes will be database-level crashes: i.e. DB server down, etc. If that’s the case, your error logging infrastructure (above) will fail (you can’t log the crash to the DB because the log tries to write to the DB). In that case, I would write failover logic in your Crash wrapper class to either

  • send an email to the admin, AND/OR
  • record the details of the crash to a plain text file

All of this sounds like an overkill, but believe me, this makes a difference in whether your application is accepted as a “stable” or “flaky”. That difference comes from the fact that all apps start as flaky/crashing all the time, but those developers that know about all issues with their app have a chance to actually fix it.

Leave a Comment