zu behandeln Ich versuche, die Erfolg/Fehler-Antworten von unserer API mit Fetch & ES6 Versprechungen intelligent zu behandeln.Cleanste Möglichkeit, benutzerdefinierte Fehler mit Fetch & ES6 Versprechen
Hier ist, wie ich brauche Antwort Zustände zu behandeln:
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
Also, ich habe Schwierigkeiten damit, wie diese sauber zu schreiben.
Ich habe etwas weniger als stellare Code arbeiten jetzt, dass wie folgt aussieht:
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)
Aber es scheint ziemlich seltsam fangen zweimal zu verwenden, und ich weiß nicht, wie mit dem 204 nur noch beschäftigen.
auch nur zu klären checkStatus
und checkErrorStatus
eine ähnliche Sache tun:
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
}
}
Irgendwelche Vorschläge für diese Reinigung?
Was ist 'parseJSON'? – Bergi
oh nur etwas einfach so: Export-Funktion parseJSON (Antwort) { zurück Antwort.json() } – jasongonzales
Für die '422' Fall siehe [diese Frage] (http://stackoverflow.com/q/29473426/1048572) – Bergi