How to parse a JSON web server response when the HTTP code is an error?

Customization

In the web application that I support, there are many AJAX calls to submit forms that look like this:

jQuery.post($form.attr("action"), $form.serialize())
    .always(commonProcessing)
    .done(function() {
        // the post succeeded, do something specific (e.g. close a dialog)
    });

The function commonProcessingsearches for the “well-known” parts in the JSON response and takes appropriate measures (the response may also include request information). He reads something like this:

function commonProcessing(result, outcome) {
    switch (outcome) {
        case "success":
            if (result.notify) {
                // show a growl-style notification
            }
            else if (...) ;
            break;
        case "error":
            // show a generic "unexpected error" notification
            break;
    }
}

Problem

HTTP - 400 - , , , " " .done ( 200 OK, , .done , "" "", "). (, notify , , ).

, HTTP jQuery , result jqXHR JSON.

: " , , , "? , , $.parseJSON(result.responseText), JSON, , jQuery, .

+5
4

try/catch ?

try{ 
     var response = $.parseJSON(response) etc 
}
catch(error){ 
     console.log(error) //error handling here
}

, , JSON, , - . , !

+2

, jqXHR, . API (), , , , - overrideMimeType(). - :

beforeSend: function(xhr){
    xhr.overrideMimeType("application/json; charset=UTF-8");
}

, AJAX ?

+1

:

$.ajax({
  url: $form.attr("action"),
  type: 'POST',
  data: $form.serialize(),
  complete: function(response) {},
  success: function(response) {},
  error: function(response) {}
});
0

My way to maintain control over the body of the error response is that I wrote my php to catch most of the things that might go wrong and still return a valid json object, and inside my JS success callback I process that object there .

success: function( response ) {
    if(response) {

    } else {

    }
},
error: function( xhr ) {
    //everything worse gets sent here
}

From now on, any truly basic error that causes an ugly error code is handled by an error callback.

-1
source

All Articles