-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Stop throwing errors and wrap JSON.parse with try/catch block #235
Comments
I believe it's correct as per the spec for fetch to throw an error if you try to get json output from a non json response… ? |
so if that were the case, how do you gracefully show the user an error
|
e.g. an endpoint suddenly returns 404 Not Found instead of normal 200 JSON
|
Because of this mess, here's the fix I wrote for this issue we have now... I basically have to do my own fetch(apiUri + path, {
method: 'GET',
headers: that.headers
})
.then((res) => {
try {
let response = JSON.parse(res);
if (response && response.error)
throw new Error(response.error);
return res.json();
} catch (e) {
return res.text();
}
})
.then((res) => {
fn(null, res);
})
.catch(function(err) {
fn(err);
}) |
We normally check the status (res.ok is handy for that) of the response before requesting json…
Also you could always implement the try catch yourself and do:-
|
I would highly recommend checking the status of the response either via |
good point |
I will close this issue then :) |
@matthew-andrews Attempting to return response.json() after reading response.ok (or response.status) throws 'Already read' log and 'undefined is not an object' error |
@sethfatz Make sure to |
Does anyone have any "real world" examples of how they're handling errors here? Particularly in react?
I'm sure it's context specific, but I'm having trouble finding good examples beyond error handling 101. |
Pretty sure I can share this without giving away too many trade secrets 😉 Premise: a successfuly query to our API endpoint returns a valid JSON packet I definitely lifted some of it from a helpful tutorial - will cite if I can find it, but worked on the error handler a lot since then
We use that everywhere, in the format
|
I think there is a good real-world solution@MDN to distinct JSON-formatted response and plain text. fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) { /* process your JSON further */ })
.catch(function(error) { console.log(error); }); |
https://github.com/github/fetch/blob/master/fetch.js#L193
See facebook/react-native#4376 for more insight.
The text was updated successfully, but these errors were encountered: