5

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

1 Answer 1

8

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
    }
})
Sign up to request clarification or add additional context in comments.

4 Comments

i don't get status == 'parseerror', if the returned data is not parseable, the status will be parseerror?
@Cacheing yes look at the $.ajax() documentation for error callback
thanks, but it should be handled this way even if the server returned some error by setting response.setStatus?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.