Check to see if you actually received JSON
You might start your code like this:
The problem is that this code makes the assumption that the response from the server contains JSON in the response body. That is a logical conclusion since you are working with a JSON API, however, any seasoned API consumer can tell you that crazy stuff happens on the server side.
There are a couple solutions here. The first is to check the HTTP status code on the response before doing anything. If it's not what you expected then don't try to parse the JSON. Here's an example:
This isn't foolproof however because it is still possible for the server to respond with a 200 status code (or the one you're expecting) and still have HTML in the response body.
In addition to checking the HTTP status code on the response, wrap the function that parses the JSON in a try/catch block. This way you can detect if there is an error parsing the response body and update the UI of your app to indicate that there was a problem to your user rather than the app abruptly ceasing to function. Here is an example:
Strictly check the structure of the JSON
When you read some documentation on the API you're working with you'll most likely see example responses. Don't assume that every response will be identical to the example. Stuff happens and sometimes properties in the JSON object are left out or are a different type than you're expecting. Always check the type of the variable before trying to use it. Additionally, check the value of the variable. As you can see in the code samples above, I'm expecting a string with a value, not an empty string. It's important to also check that the string has a value. Here is an example:
At this point we have a great function checks which for many possible errors in the XHR response. However, if we leave the code like this, we'll be flying blind. That is, we'll have no idea how many times each error is occuring. When you get a bug report, in order to prioritize it, it's extremely helpful to know the scope (or how many times it is occuring in the wild). If you're using Google Analytics, you can do this easily with custom events. Here is an example:
Now we've checked for almost every type of problem with the response on the XHR request and we will know exactly how many times each problem will occur.
You should follow me on Twitter: @kylerush