Skip to content

Instantly share code, notes, and snippets.

@dav1app
Last active April 18, 2021 00:42
Show Gist options
  • Save dav1app/66bca5eefcdfe2e6484d4c7707c07e4b to your computer and use it in GitHub Desktop.
Save dav1app/66bca5eefcdfe2e6484d4c7707c07e4b to your computer and use it in GitHub Desktop.
Bullet-proof fetch response handler
/**
* This is my attempt to create a bullet-proof response handler for fetch.
*
* The idea is that no metter what happens to the response, the components
* should receive a response that can be used in a `catch` block.
*
* I am using this gist quite a lot.
*
* @author dav1app
* @version 1.0.0
*/
const responseType = 'json'
const response = fetch(destination, request)
//Basic handler for the response.
.then((rawResponse) => {
if (rawResponse.ok) {
return rawResponse
} else {
throw rawResponse
}
})
.catch((rawResponse) => {
return rawResponse[responseType]()
//This is triggered when your response body can be handled.
.then((errBody) => {
switch (true) {
case typeof errBody === 'string':
return new Error(errBody)
case !!errBody.message:
return new Error(errBody.message)
case !!errBody.errMessage:
return new Error(errBody.errMessage)
default:
return new Error(errBody || 'Unknown Error')
}
})
//this is triggered when you cannot parse your body.
.catch((err) => {
switch (true) {
case !!rawResponse.message:
return new Error(rawResponse.message)
case !!rawResponse.statusText:
return new Error(rawResponse.statusText)
case !!rawResponse.status:
return new Error(rawResponse.status)
case !!rawResponse:
return new Error(rawResponse)
case err instanceof Error:
return err
}
})
.then((parsedError) => {
throw parsedError
})
})
//This handles when you get something like 201, but without body.
.then((rawResponse) => {
return rawResponse[responseType]().catch((err) => true)
})
.then((parsedResponse) => {
return parsedResponse
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment