I am trying to intelligently handle the success/error responses from our API using fetch & ES6 promises.
Here is how I need to handle response statuses:
204: has no json response, but need to treat as success
406: should redirect to sign in
422: has json for error message
< 400 (but not 204): success, will have json
>= 400 (but not 422): error, will not have json
So, I am struggling with how to write this cleanly.
I have some less than stellar code working right now that looks like this:
fetch()
.then(response => checkStatus(response))
.then(parseJSON) //will throw for the 204
.then(data => notify('success', someMsg))
.catch(error => checkErrorStatus(error))
.then(parseJSON)
.then(data => notify('error', dataForMsg)
.catch(error => notify('error', someGenericErrorMsg)
But it seems pretty weird to use catch twice and I don't know how to deal with that 204 just yet.
Also, just to clarify checkStatus
and checkErrorStatus
do a similar thing:
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
let error = new Error(response.statusText)
error.response = response
throw error
}
}
function checkErrorStatus(error) {
if(error.response.status === 422) {
return error.response
} else {
let error = new Error(response.statusText)
error.response = response
throw error
}
}
Any suggestions for cleaning this up?
Following on from Bergi's solution, you might consider mechanising the handling of responses with a fairly simple
ResponseHandler()
object;In use :
You would lose the efficiencies of a hard coded solution such as Bergi's, but potentially benefit from improved manageability and reusability.
I think you can write it out pretty easily: