javascript - 获取 API 错误处理

标签 javascript reactjs error-handling fetch-api

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

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

这是示例,登录操作:

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
    })
  })
    
}

最佳答案

使用以下解决方案可以处理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);
        }
    });

关于javascript - 获取 API 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50330795/

相关文章:

inheritance - 如何在 React 组件和 es6 类中使用继承

vb.net - 尝试多种捕获行为

ios - 尝试将数据从Parse填充到CollectionView中时出现查询错误

java - 即使在 StackOverflow 之后代码也能正常工作 - 怎么样?

php - 如何使用javascript将相同的变量从php发送到两个不同的php页面

javascript - sahi:如何在javascript中使用转义字符

javascript - 哪些 HTTP header 可以用来判断浏览器是否启用了 javascript?

javascript - Jest - React 组件中的模拟粗箭头功能

javascript - React Navigation header onPress - this.setState 不是一个函数

javascript - 识别 Javascript 中的按钮按下事件