获取 API 错误处理

IT技术 javascript reactjs error-handling fetch
2021-04-30 04:55:25

我想显示来自我的 API 的错误消息,问题是如果我检查,我无法到达该错误response.ok,它返回 Fetch 错误,而不是来自 API 的错误。

如果我不使用if(response.ok)...它,它会从 API 返回错误,但它会调度成功操作。

这是示例,登录操作:

export const signIn = data => dispatch => {
  dispatch({ 
    type: SIGN_IN
    }) 
  fetch(API_URL+'/login', { 
   method: 'POST',
   headers: {
      'content-type': 'application/json'
      },
   body: JSON.stringify(data),
    })
    .then( response => {
    if (!response.ok) { throw response }
    return response.json()  //we only get here if there is no error
  })
  .then( json => {
    dispatch({
      type: SIGN_IN_SUCCESS, payload: json
    }),
    localStorage.setItem("token", 'Bearer '+json.token)
    localStorage.setItem("user", JSON.stringify(json.user))
  })
  .catch( err => {
    dispatch({
      type: SIGN_IN_FAILED, payload: err
    })
  })
    
}

这是发送正确消息但作为成功操作而不是失败操作的操作代码。

export const signIn = data => dispatch => {
  dispatch({ 
    type: SIGN_IN
    }) 
  fetch(API_URL+'/login', { 
   method: 'POST',
   headers: {
      'content-type': 'application/json'
      },
   body: JSON.stringify(data),
    })
    .then( response => response.json())
  .then( json => {
    dispatch({
      type: SIGN_IN_SUCCESS, payload: json
    }),
    localStorage.setItem("token", 'Bearer '+json.token)
    localStorage.setItem("user", JSON.stringify(json.user))
  })
  .catch( err => {
    dispatch({
      type: SIGN_IN_FAILED, payload: err
    })
  })
    
}

3个回答

根据本条

根据 MDNfetch()API 仅在以下情况下拒绝Promise

“遇到网络错误,尽管这通常意味着权限问题或类似问题。”

基本上fetch()只会在用户离线时拒绝Promise,或者发生一些不太可能的网络错误,例如 DNS 查找失败。

然后,您可以使用这部分代码来使用非网络错误处理并使您的代码更具可读性

function handleErrors(response) {
    if (!response.ok) throw new Error(response.status);
    return response;
}

fetch("API URL")
    // handle network err/success
    .then(handleErrors)
    // use response of network on fetch Promise resolve
    .then(response => console.log("ok") )
    // handle fetch Promise error
    .catch(error => console.log(error) );

为了在出现某些错误时从服务器提取 API 消息,您必须使用以下习语(尽管表面上并不存在),请参阅链接

     fetch("http://localhost:8090/test/error", {
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        }
    })
        .then(result => {
            //Here body is not ready yet, throw promise
            if (!result.ok) throw result;
            return result.json();
        })
        .then(result => {
            //Successful request processing
            console.log(result);
        }).catch(error => {
            //Here is still promise
            console.log(error);
            error.json().then((body) => {
                //Here is already the payload from API
                console.log(body);
            });
        })

详细 - 是的!,但正是需要的。

使用以下解决方案可以处理JSON API 错误、通用 API 错误通用提取错误

fetch("api/v1/demo", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        "data": "demo"
    })
})
    .then(response => {
        if (!response.ok) {
            return Promise.reject(response);
        }
        return response.json();
    })
    .then(data => {
        console.log("Success");
        console.log(data);
    })
    .catch(error => {
        if (typeof error.json === "function") {
            error.json().then(jsonError => {
                console.log("Json error from API");
                console.log(jsonError);
            }).catch(genericError => {
                console.log("Generic error from API");
                console.log(error.statusText);
            });
        } else {
            console.log("Fetch error");
            console.log(error);
        }
    });