How to handle error from JSON.parse
See original GitHub issueThe 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.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:24
- Comments:21 (2 by maintainers)
Top GitHub Comments
Just got burned on this. Instead of correctly rejecting the promise on invalid (truncated) JSON, it simply returns the orignal string object. Bad bad bad. At least put a warning in the docs about this.
@emilyemorehouse is this something you could fix, for the sake of all humanity?