使用fetch和ES6承诺处理自定义错误的最简洁方法

jas*_*les 8 javascript promise ecmascript-6 es6-promise fetch-api

我正在尝试使用fetch和ES6 promises智能地处理来自API的成功/错误响应.

以下是我需要处理响应状态的方法:

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
Run Code Online (Sandbox Code Playgroud)

所以,我正在努力学习如何干净利落地写这个.

我现在有一些不太常用的代码,看起来像这样:

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)
Run Code Online (Sandbox Code Playgroud)

但是使用catch两次似乎很奇怪,我还不知道如何处理204.

另外,只是澄清checkStatuscheckErrorStatus做类似的事情:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

有关清理的建议吗?

Ber*_*rgi 19

我想你可以很容易地写出来:

fetch(…).then(response => {
    if (response.ok)
        return response[response.status == 204 ? "text" : "json"]();
    if (response.status == 422)
        return response.json().then(err => { throw err; });
    if (response.status == 406)
        var error = new AuthentificationError(response.statusText); // or whatever
    else
        var error = new Error(response.statusText)
    error.response = response
    throw error;
})
Run Code Online (Sandbox Code Playgroud)