简体   繁体   English

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

[英]How catch error from async action with redux?

I have fetch, it throws error: 我获取了,它引发错误:

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();
    });
},

then this async action (redux): 然后执行以下异步操作(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));
    }
}

next: 下一个:

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

And now I want catch Error from my fetch : 现在我想从提取中捕获Error:

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

How to catch it correctly? 如何正确捕捉? My code doesn't do this stuff. 我的代码没有做这些事情。 Thanks! 谢谢!

You can throw error from .catch() , substitute Promise.prototype.catch() for try..catch 您可以从.catch() throw错误,用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); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM