How to handle Ajax requests with business error?

Asked

Viewed 1,107 times

4

I searched the Internet and I still haven’t found an answer mature enough for a problem.

I have an Ajax request and taking out errors released by the application as a possible connection drop, for example, I don’t want to throw an exception if I have a business error.

For example, the user enters an invalid email address in the email field. I want to throw an error, but not as a request error so that the object error function jQuery ajax treat it. I don’t want something like 400 and 500 range HTTP errors.

I want to return status 200 as the request was successful, but somehow identify that there was a business error.

I see a lot of people returning an object JSON with a successful/failed Boolean attribute and if this same object is failed it has another Jsonarray object with the error messages.

This would be the best way to really drive when there is a business error and not infrastructure or application itself?

  • The status code 400 is precisely to represent a customer error. If the customer sends a poorly formatted email then it is a customer error. Conceptually, it is wrong to treat as a success a request that did not meet the necessary prerequisites and had to be aborted. Conceptually you do not have a "success". Now if Voce has some limitation and can not implement the answer code 400 there is another story.

  • Type 400 errors cover business error? A user who sends an invalid URL, or a string instead of a numeric field, and so on? These errors should be treated by the range 400?

  • See my answer below

1 answer

2


Not, this is not the best way. You should return an error 400. HTTP is an application protocol and therefore if you return 2xx code the client can assume that your request has been accepted independent of any content from the body of the response.

Of Restful Web Services Cookbook:

A common error that some web services make is to return a status code that reflects success but include a message in the body of the response that describes an error condition. By doing this you prevent HTTP-based applications from detecting errors. For example, the cache (browser, or a reverse proxy for example) will store this response as a successful response and serve it to the next customers, even when customers were able to make a correct request.

Use 4xx code when the client is able to correct your request and resend correctly, use 5xx code when it is a server error and regardless of a fix in the request it makes no sense to resend it.

RESPONSE BASED ON https://stackoverflow.com/questions/9381520/what-is-the-appropriate-http-status-code-response-for-a-general-unsuccessful-req

Browser other questions tagged

You are not signed in. Login or sign up in order to post.