Error handling in REST applications : best practices

RESTful error handling gives a nice overview of the miscellaneous ways of handling errors in a RESTful web application. To me, the following criteria need to be met to provide decent REST error handling :

  • Be simple to implement (or at least, be simple for simple cases)
  • Be machine-parseable (so that intelligent REST clients can be built)
  • Be human-readable (so you don’t have to fire up your HTTP sniffer to understand what went wront, when you’re developping a client)
  • Follows HTTP semantics, so proxies, caching, etc continues to work correctly

None of the ideas suggested in the article match all of my criteria, so here is the solution I would suggest :

  • ALWAYS return the most appropriate HTTP error code whenever an application error happens. Sure, it might not map perfectly, but choose the one that expresses the concept correctly. It is totally absurd to always use 200 error codes, even the SOAP guys have not made that mistake ! Also make sure to use a server-side REST framework that will automatically handle common errors for you (405 for unsupported methods, etc..)
  • When the same HTTP error code maps to several application errors, add an ADDITIONAL X-Application-Error-Code : header that provides a simple string allowing to remove ambiguity (choose a simple all-ASCII exception name). This will allow creating simple clients that can easily parse exceptions without too much burden for simple cases
  • Add a body that allows a human being (for instance, the developer of a REST client for your service) to instantly understand what went wrong. This can take the form of either a free-form response, or a fully-parseable (XML, JSON, whatever) response body that contains a message field.
  • Only implement the fully-parseable response body when your application has matured. Do it smartly, avoid working weeks on your service before even displaying the first feature to your user ;-)

2 Responses to “Error handling in REST applications : best practices”

  1. Harm says:

    Aha! This additional header makes a lot of sense. I’ve been breaking my head over this all day. Thanks.

  2. Sephali says:

    Hi. Nice info.

Leave a Reply