Skip to content

Instantly share code, notes, and snippets.

@dreamerkumar
Created April 21, 2020 21:52
Show Gist options
  • Save dreamerkumar/1c26aa970598d9ade62c621bba781f85 to your computer and use it in GitHub Desktop.
Save dreamerkumar/1c26aa970598d9ade62c621bba781f85 to your computer and use it in GitHub Desktop.
Handle succcess and error responses for fetch calls, including scenarios where network error won't return a response body. Attempt to squeeze out all necessary info from success as well as failures.
fetch('/api/sendMessage', {
method: 'POST',
body: JSON.stringify(bodyObj),
headers: new Headers({
'Content-Type': 'application/json',
}),
})
.then((res) => this.handlePushNotificationResponse(res))
.catch((res) => this.handlePushNotificationResponse(res));
handlePushNotificationResponse(res) {
if (!res) {
console.error('Error occurred while trying to read the fetch response');
this.showError(res);
} else if(!res.ok) {
this.showError(res);
} else {
this.showSuccess(res);
}
}
showSuccess(res) {
this.setState({hasResults: true, isLoading: false, results: 'success'});
this.logSuccessResponse(res);
}
logSuccessResponse(res) {
const statusText = `Push notification call succeeded:: Fetch statusText: ${res && res.statusText}`;
if (res && res.json) {
res.json().then(body => console.info(`${statusText}, Response body:`, body))
.catch(() => console.info(`${statusText}, No further info available as api error response body could not be parsed.`));
} else {
console.info(statusText);
}
}
showError(res) {
this.setState({hasErrors: true, isLoading: false, errors: 'error'});
this.logErrorResponse(res);
}
logErrorResponse(res) {
const statusText = `Push notification call failed:: Fetch statusText: ${res && res.statusText}`;
if (res && res.json) {
res.json().then(err => console.error(`${statusText}, `, err))
.catch(() => console.error(`${statusText}, No further info available as api error response body could not be parsed.`));
} else {
console.error(statusText);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment