How to handle REST Exceptions?

前端 未结 2 1669
礼貌的吻别
礼貌的吻别 2020-12-15 11:28

We are in the middle of a ongoing discussion about how to handle REST exceptions.

Response Content type : JSON

Two solutions we have:

  1. Throw all
相关标签:
2条回答
  • 2020-12-15 12:02

    Use error codes like for HTTP. So 50* for any exception cause by some internal problem. And 40* for bad arguments. Avoid using your own defined codes as far as its possible. The idea is to have a "uniform" interface.

    In general. 204 for success without sending any content 200 for success with a json representation of the resource And if its not a successful operation return appropriate response code. You can choose to optionally return a json. To simplify things you can have a common format (json) for all error responses.

    http://en.wikipedia.org/wiki/REST is a must read before you freeze on your api specs.

    0 讨论(0)
  • 2020-12-15 12:13

    For a JSON API I recently developed I do both. I always respond with valid JSON (well, assuming I respond at all). If I detect an invalid request, I use status 400. If I detect a server error (which I don't believe is caused by an invalid request), I use a 5xx status. The JSON object contains a special key that is only set for errors, with a string value.

    I think this is a good solution that respects REST principles, and can be used in multiple ways. The same solution is used by some other JSON APIs, such as Yahoo Search. Try http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&output=json .

    0 讨论(0)
提交回复
热议问题