Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices for sending error responses in JSON web services?

What is the best practice with regard to sending error responses in a JSON web service? I have seen it done several ways and wanted to know whether there were any agreed-upon standards or best practices among the choices.

I've seen it done where the response includes indication of success or failure as well as the data to be returned or a suitable error message, e.g.

[{'success':true, 'data':{...}]
[{'success':false, 'data':{'message':'error'}]

But I've also seen examples where the JSON object only includes data, and the service uses the normal HTTP error codes to indicate a problem (403, 404, 500, etc). (This is how the Twitter API does it.)

Is there a "right" way to do this, or is it just a matter of style? Is the latter method more "RESTful?"

like image 671
Jamie Forrest Avatar asked Feb 04 '12 14:02

Jamie Forrest


People also ask

Do you send error message if you code REST API?

The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.


2 Answers

In a "RESTful" approach, the primary error response is indicated by an appropriate status code (4xx/5xx).

Your message should provide addtional, application-specific hints on how to recover from the error. This may include human-readable representations of the error that has occured or some kind of more technical indicator (i.e. providing an Exception class name).

For being generic, keep to a fix syntax for your error messages. This allows you to introduce new error messages withour breaking the clients.

like image 114
b_erb Avatar answered Oct 12 '22 16:10

b_erb


Use the appropriate HTTP codes and put what you now call "data" as the body of the response. This is the only correcty RESTful way to make the API users aware of an error.

Just doing this will not make your API RESTful, but not doing it will surely make your API non RESTful.

An example of well-used HTTP status codes for errors is in the Dropbox API reference, have a look at the "Errors" sections under each method, they explain which error codes you should expect and what is the associated meaning in that particular method.

like image 30
gioele Avatar answered Oct 12 '22 16:10

gioele