简体   繁体   中英

Error handling in Rest

There are many ways to handle errors in RESTful api:s. Simplifying a solution is sometimes a need becase of system requirements and domain policys. Stack Overflow is doing a simplification with their own api using the http status code 400 for all errors ( https://api.stackexchange.com/docs/errors ) and then embedding their own error codes in the respons.

This is a solution that does follow the REST pattern but probably have other advantages. One advantage I can think of is that error codes within the response can be more system specific than using only errors available in the http protocol. Is there any more advantages of using the Stackoverflow pattern for handling REST errors?

I think that you must leverage the HTTP status codes to notify the REST client what happens (if processing is successful, if an error occurs) but this corresponds to high-level hints.

You generally need to associate an error payload that provides a thinnest description(s) of the error(s) and something structured so programmatic REST client can understand and handle them. You are free to choose the structure of such payload.

Here are what I commonly use (described using the JSON format but it's not linked to a particular format):

{
  errors: [
    {
      "message": "my message",
      "code": "ERR12",
    },
    {
      "message": "my message",
      "code": "ERR13",
      "field": "fieldName"
    }
  ]
}

Some errors can be general but also linked to a particular field of the request representation.

Moreover I think that we can leverage than other 4xx codes since the code 400 is a bit general. Here are some than could be used:

  • 400 : a general error telling the request isn't correct
  • 405 : if you try to use an HTTP method that isn't supported by the resource
  • 409 : error with optimistic locking
  • 412 : if the preconditions fail before executing the processing of the resource method
  • 415 : if the format of the provided representation isn't correct or the requested media type isn't supported
  • 422 : error when validating the input representation. Whereas it comes from WebDAV, you could use it (see for example the Github API).

You can notice that some of these methods ( 405 , 415 ) are natively supported by REST frameworks (for example Restlet).

In the context of Restlet, the error management can be done like described in this answer: JSON Representation of a HTTP 400 for Restlet Client . This can give you some hints for your implementation even without this framework.

Hope it helps, Thierry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM