2017年12月19日星期二

Readings on error code design of RESTful services

Having written serious RESTful services to some extent, you'll end up thinking about your error codes. Chances are that you had adopted a few HTTP error codes (404, 500, etc.) in your service but realized at some point that these are just not enough to describe all possible erroneous scenarios. Because HTTP error code is essentially designed for web pages and browsers, not specifically for web services.

http://blog.restcase.com/rest-api-error-codes-101/ is a nice piece of writing in this regard. It compares two different perspectives on how we treat HTTP error codes and how we integrate them with customized error codes in the services. It also proposed a practical approach of error code design. Key aspects:


  • Use only a small, well-known subset (less than 10) of HTTP status codes: 404 is good while 418 only makes sense to a handful of people.
  • Return HTTP status code 2XX only if everything works out OK.
  • Use HTTP status code where appropriate: 401 if authentication is needed, 404 if you couldn't find a resource (not just the API itself doesn't exist), etc.
  • Consider if the client should re-submit the request without any modification after this error when choosing a HTTP error code.
  • If an erroneous situation doesn't fall into any category that your chosen set of HTTP status codes could represent, return a general code (400 for client side error, 500 for server side error) in the HTTP header, and include a customized, more meaningful error code in the HTTP body.


Refer also to the following FAQs.

https://softwareengineering.stackexchange.com/questions/203492/when-to-use-http-status-code-404-in-an-api

https://stackoverflow.com/questions/942951/rest-api-error-return-good-practices

没有评论:

发表评论