How to make jQuery parse my error response represented as a valid json?

For an error message with a non-2001HTTP status code, the content will not be parsed by jQuery. If you'd really like not to parse the returned result to JSON yourself, you would have to return a HTTP status 200 and use the success (done) callbacks.

It's a good sign that you're using (from your example) HTTP code 409, and I think you should keep doing that - just bite the bullet and parse the JSON manually in your error handler. If the parsing fails, something else has gone wrong (like a temporary network failure), but this will allow you to build a nice API that you (and possibly others) can consume without having to build too much error checking into the success function.

Keep success for the happy results, and error for unhappy results.

1 Technically any 2xx status should be considered successful; in jQuery (status >= 200 && status < 300 || status === 304) counts as something successful.


Call $.parseJSON explicitly in your error callback:

(...)
.error(function (err) {
  var msg = $.parseJSON(err).msg;
  alert(msg);
});

I ran into the same issue and found a slightly different way from @Barmar's answer.

Aswell as responseText, there is also a responseJSON property, so you could do the following:

var json_response = err.responseJSON.msg;

If you console.log(err); there's a few properties in there that you might wish to use in your error message on the page.

Tags:

Ajax

Jquery