如何通过redux捕获异步操作的错误?

时间:2016-09-03 23:57:03

标签: javascript promise try-catch redux fetch

我有提取,它会抛出错误:

fetchAuthorization(username, password) {
    return fetch(`https://api.github.com/user`, {
        method: 'GET',
        headers: {
            "Accept": 'application/json',
            "Content-Type": 'application/json',
            "Authorization": "Basic " + btoa(`${username}:${password}`)
        },
    })
    .then(res => {
        if(res.status !== 200) {
            throw Error("Bad validation");
        }
        return res.json();
    });
},

然后这个异步动作(redux):

export const onSignInAction = (username, password) => {
    return dispatch => {
        return api.fetchAuthorization(username, password)
            .then( res => {
                dispatch(signInAction(username, password, res));
            })
            .catch(err => console.log(err));
    }
}

下一个:

handleSignIn = (username, password) => {
    const { onSignInAction } = this.props;
    onSignInAction(username, password);
}

现在我想从我的抓取中捕获错误:

handleSignIn = () => {
    const { onSignIn } = this.props;
    const { errorMessage, open } = this.state;
    const username = this.usernameField.getValue();
    const password = this.passwordField.getValue();
    try {
        onSignIn(username, password);
    }
    catch (Error) {
        this.setState({
            errorMessage: 'Incorrect username or password'
        });
    }
}

如何正确捕捉它?我的代码不做这个东西。谢谢!

1 个答案:

答案 0 :(得分:0)

throw可能会出现.catch()错误,Promise.prototype.catch()代替try..catch



var onSignInAction = () => {
  return Promise.reject(new Error("Bad validation")).catch(e => {
    console.log("catch 1", e.message);
    throw e
  });
}

onSignInAction()
.catch(err => {
  console.log("catch 2:", {
    errorMessage: 'Incorrect username or password'
  }, err.message);
});