Javascript 使用Axios全局处理请求超时错误并向用户显示警报的最佳方法?

Javascript 使用Axios全局处理请求超时错误并向用户显示警报的最佳方法?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,这是我当前处理请求错误的设置: 当按下login函数时,就会执行这个“loginButtonHandler()”,我正在执行“authAPi.login()”函数并等待看到结果。如果结果成功,我将导航到应用程序,如果不是,我将更改状态以显示错误消息 async function loginButtonHandler() { const result = await authAPI.login(formInput) if (result.success) { pro

这是我当前处理请求错误的设置:

当按下login函数时,就会执行这个“loginButtonHandler()”,我正在执行“authAPi.login()”函数并等待看到结果。如果结果成功,我将导航到应用程序,如果不是,我将更改状态以显示错误消息

async function loginButtonHandler() {
    const result = await authAPI.login(formInput)
    if (result.success) {
        props.navigation.navigate('App')
    } else {
        setLoginError(result.error)
    }
}
在我的“authAPI.login()”中,我尝试执行登录POST请求,将令牌存储在本地存储器中,在Axios默认头中设置令牌,最后返回success=True

export async function login(data){
    try {
        // Send login request to server and get token
        const response = await axios.post('auth/login/', data)
        const token = response.data.key

        // Save token on local storage
        await AsyncStorage.setItem('token', token)

        // Set token in default request headers
        axios.defaults.headers.common['Authorization'] = `Token ${token}`

        // If success return true
        return {success: true}
    }
    catch (error) {
        // If timeout is triggered (error.code='ECONNABORTED') show alert to user.
        if (error.code === 'ECONNABORTED'){
            Alert.alert("Error",  'Connection to server timeout.')
            return {success: false }
        }

        // If server responds with wrong credentials
        if (error.response.data['non_field_errors'][0] === 'Unable to log in with provided credentials.'){
            return {success: false, error: 'Wrong username or password.'}
        }

        // For unforeseen errors throw the error
        throw error
    }
}
目前,如果我想向服务器添加更多具有请求的函数,我需要将此错误处理添加到所有请求函数捕获块:

catch (error) {
    if (error.code === 'ECONNABORTED'){
        Alert.alert("Error",  'Connection to server timeout.')
        return {success: false }
    }
    ...
我正试图找到一种全局添加此错误处理的方法,这样用户就可以获得任何请求超时的警报,而无需将其添加到每个请求中

我可以添加这个拦截器:

instance.interceptors.response.use((response)=> response, (error)=> {
    if (error.code === 'ECONNABORTED') {
        Alert.alert("Error",  'Connection to server timeout.')
    }

    return Promise.reject(error);
  })
但这似乎没有帮助,因为我似乎仍然需要将此添加到所有请求错误捕获块中:

    if (error.code === 'ECONNABORTED'){
        return {success: false }
    }
我就是这样做的

    if (response.ok) {
    // do data conversion here if needed
    AsyncStorage.setItem('token', response.data.access_token);
    AsyncStorage.setItem('refresh_token', response.data.refresh_token);
    AsyncStorage.setItem('clientId', response.data.clientId);

    yield put(SigninActions.signinSuccess(response.data));
  } else if (
    response.problem === 'NETWORK_ERROR' ||
    response.problem === 'TIMEOUT_ERROR'
  ) {
    yield put(
      SigninActions.signinFailure(
        'There is a network problem. Please try again.',
      ),
    );
  }
您可以使用此超级库显示警报: 我就是这样做的

    if (response.ok) {
    // do data conversion here if needed
    AsyncStorage.setItem('token', response.data.access_token);
    AsyncStorage.setItem('refresh_token', response.data.refresh_token);
    AsyncStorage.setItem('clientId', response.data.clientId);

    yield put(SigninActions.signinSuccess(response.data));
  } else if (
    response.problem === 'NETWORK_ERROR' ||
    response.problem === 'TIMEOUT_ERROR'
  ) {
    yield put(
      SigninActions.signinFailure(
        'There is a network problem. Please try again.',
      ),
    );
  }
您可以使用此超级库显示警报: