处理react native / redux中的fetch错误

时间:2018-04-13 11:59:21

标签: reactjs react-native redux

我已按如下方式设置登录操作创建者。

成功登录在具有200状态的try块中发生。所有失败的登录都会在catch块401中结束,如果我关闭服务器,请求将返回Network Error

有没有更好/标准的方法来处理这个问题?特别是因为在大型应用程序中,显然有许多不同的端点可供请求,所以似乎没必要每次都重写网络错误代码。

export const handleLogin = data => async (dispatch) => {
  try {
    const res = await axios.post(
        `http://${SERVERURL}/auth/login`, data
    );
    console.log('200 status');
    dispatch({ type: LOGIN_SUCCESS, payload: res.data });
    // AsyncStorage.setItem(JWT_BEARER_TOKEN, res.data.token);
  } catch (e) {
    if (e.response && e.response.status === 401) {
      console.log('Login Failed');
      dispatch({ type: LOGIN_FAILURE, payload: e.response.data });
    } else {
      console.error('Server / Network Error');
      dispatch({ type: NETWORK_ERROR, payload: e.response });
    }
  }
};

根据@Pritish Vaidya的答案进行更新。

所以使用你建议的答案,我应该处理登录成功失败吗?

export const handleLogin = data => async (dispatch) => {
  const res = await axiosInstance.post('/auth/login', data);
  if (res.status && res.status === 200) {
    dispatch({ type: LOGIN_SUCCESS, payload: res.data });
  } else {
    dispatch({ type: LOGIN_FAILURE, payload: null });
  }
};

并弄清楚如何在dispatch之后Network Error传递// ... }, (error) => { if (!error.response) { return dispatch({ type: 'NETWORK_FAILURE' payload: null }); } } // ...

class Category(models.Model):
    name = models.CharField('Name', unique=True, max_length=35)
    description = models.CharField('Description', max_length=255)
    slug = models.SlugField('Shortcut')

class Source(models.Model):
    name = models.CharField('Name', unique=True, max_length=35)
    description = models.CharField('Description', max_length=255)

class CategorySource(models.Model):
    category = models.ForeignKey(Category, related_name='category_source')
    source = models.ForeignKey(Source, related_name='category_source')
    url = models.CharField('RSS Feed Url', max_length=2000)

1 个答案:

答案 0 :(得分:2)

由于您已经在使用axios,因此可以通过以下方式处理错误。

Axios提供请求middlewares / interceptors轻松实现

根据您的问题,您需要一个响应中间件

<强>用法

<强> Interceptor.js

const AxiosInstance = axios.create({
    baseURL: SERVER_URL,
    timeout: 20000,
    headers: {
        'Content-Type': 'application/json'
    }
})


 AxiosInstance.interceptors.response.use((response) =>{
    // handle the response after it is received
    return response;
}, (error) => {
    if (!error.response) {
        // Network error
        // handle the network error here
        // Get the instance of the store here
         store.dispatch(// Your action))
    }
    else {
        // handle the errors due to the status code here
        const code = error.response.status

        // handle the errors due to response data here
        const response = error.response.data
    }

})
export default AxiosInstance