Error Handling in PHP

Ian Littman / @iansltx ||

Good for 204, bad for 500

What we'll cover

  1. Handling fatals sanely
  2. Handling exceptions exceptionally
  3. Handling non-fatals silently
  4. Knowing when your site errors
  5. Using other people's work for 1-4


don't copy-paste this code

So far so good

Some boilerplate

a wild error appeared!

blank handling

add a shutdown handler


  • HHVM can actually catch these errors
    • Needs a configuration value set
    • Error code is 2^24
  • Your handler MUST set a proper response code
    • Default is 200...
    • ...even when it would otherwise be a 500

What about exceptions?

catch all the exceptions

#0 /home/yanntxin/public_html/err/index.php(13): {closure}(Array, Array, Array) #1 {main}

What about notices?

Hey dude...wait, what???

send the notices somewhere


  • Unless your error handler returns false, PHP's won't be called after yours is done
  • If you handle a fatal, it's your job to call die()...
  • ...and set the HTTP response code

irl (In real life)

  • You'll probably use a class for this sort of thing
    • String function names and [$this, 'method'] syntax work for callback registering
    • Your definition of what a fatal error is can be a constant expression in PHP 5.6+
    • You'll probably handle all errors with one handler

irl (In real life)

  • You'll want to do non-trivial logging
    • Your logger should be fine when your system fatals
    • Use a PSR-3 logger (e.g. Monolog)
    • Set alerts from your app, e.g. text + email on a 500

irl (In real life)

that's it!



Ian Littman / @iansltx ||

Code at

Error Handling in PHP

By Ian Littman

Error Handling in PHP

  • 1,953
Loading comments...

More from Ian Littman