Created
April 21, 2020 21:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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