Define error structure in a REST API

What are the best practices for the structure of an error in a REST API? I know that I should use the codes in HTTP to describe it (REST API error return good practices), but a structure is always useful, and I found myself always using something like a type of error and a reason of the error (raise CanNotCreate('Because of this') ).

What are the best practices to define the structure of an error message? Can you give an example of any particular API with a good error handling?


I usually indicate the 'type' in the Reason-Phrase of the response status (for example: 409 Cannot Create instead of the more typical 409 Conflict ), because it's machine-parsable without having to parse media types like HTML, XML, or JSON. In general, the Reason-Phrase is enough for machine clients to do whatever is appropriate, particularly when a given resource might return the same code for slightly different reasons.

Then, in the response body, include more information for both programmers and end users in the same media type you use elsewhere; if the request had succeeded and returned 200 OK with JSON, for example, then return JSON with your error response. Doing otherwise really frustrates folks developing against your API.

Finally, if your media-type allows it, include hyperlinks if at all possible in the response that assist the client in navigating solutions to the problem.

链接地址: http://www.djcxy.com/p/45330.html

上一篇: WCF REST + Windsor错误处理

下一篇: 在REST API中定义错误结构