如何使用 redux 从异步操作中捕获错误?

How catch error from async action with redux?

我有获取,它抛出错误:

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

如何正确捕捉?我的代码不做这些事情。谢谢!

您可以 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);
});