-
-
Notifications
You must be signed in to change notification settings - Fork 11.6k
How to handle error from JSON.parse #61
Description
The transformRequest method attempts to parse JSON, but swallows any error in an empty catch statement. This results in the stringified form of the response body to be returned should the JSON be malformed, and supplied to the response object that is used to resolve the Promise.
Without the try/catch a global error would occur. With the try/catch the code handling the response will error, but in an unpredictable way. Consider:
// Assume a malformed response from the server for the request.
// Missing quotes around property names:
// {firstName: "Jimmy", lastName: "Page", isBlocked: true}
axios.get('/user/12345').then((res) => {
var user = res.data;
if (!user.isBlocked) {
// Do something potentially dangerous that only an unblocked user should be allowed to do
}
});In this case user is a String not an Object as expected. Calling 'some string'.isBlocked will return undefined, which evaluates as falsey. This will cause the if condition to erroneously be entered.
A potential solution would be to reject the Promise if JSON.parse throws an Error. This isn't a straight forward fix though as it would break #55 again.