jquery.getJSON() error handling

11,104

Since the $.getJSON() returns a promise object uou can use the .fail() promise callback for case 2 and 3... case 1 needs to be handled in the success callback itself

jQuery.getJSON(...).fail(function(jqXHR, status, error){
    if(status == 'parseerror'){
        //not valid json
    } else {
        //some other error
    }
})
Share:
11,104
Cacheing
Author by

Cacheing

Updated on June 19, 2022

Comments

  • Cacheing
    Cacheing almost 2 years

    I am using jquery.getJSON(), but I don't know how to do error handling. And these are some situations that I need to handle.

    1) what if the returned data is null?

    2) what if the returned data is not json parseable?

    3) what if some error message is returned? For example, the server returned HTTP ERROR

  • Cacheing
    Cacheing over 10 years
    i don't get status == 'parseerror', if the returned data is not parseable, the status will be parseerror?
  • Arun P Johny
    Arun P Johny over 10 years
    @Cacheing yes look at the $.ajax() documentation for error callback
  • Cacheing
    Cacheing over 10 years
    thanks, but it should be handled this way even if the server returned some error by setting response.setStatus?
  • Arun P Johny
    Arun P Johny over 10 years
    @Cacheing yes... then the status will be error and you can use jqXHR.status to get the response status like 400/404/403/500 etc... also you can read the response content using jqXHR.responseText
  • Cacheing
    Cacheing over 10 years
    Thank you very much. This is very helpful!