获取 API 错误处理 [英] Fetch API error handling

查看:32
本文介绍了获取 API 错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示来自我的 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
    })
  })
    
}

推荐答案

根据这篇文章 :

每个 MDNfetch() 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) );

这篇关于获取 API 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆