获取 API 错误处理

2022-01-20 00:00:00 reactjs error-handling fetch javascript

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

I want to display error message from my API, problem is that I can't reach that error if I check for response.ok, it returns Fetch error, not the one from API..

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

If I don't use if(response.ok)... it returns the error from API but it dispatches the success action.

这里是示例,登录操作:

Here is the example, login action:

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

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

This is the code for action that dispatches the right message but as success action, not as failed one..

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

推荐答案

根据这篇文章 :

每个 MDN,fetch() API 仅在

一个网络遇到错误,尽管这通常意味着权限问题或类似的."

"a network error is encountered, although this usually means permissions issues or similar."

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

Basically fetch() will only reject a promise if the user is offline, or some unlikely networking error occurs, such a DNS lookup failure.

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

then, you can use this part of code to use non-network error handlings and make your code more readable

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

相关文章