Sergey Korotenko Sergey Korotenko - 3 months ago 5
Javascript Question

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):

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 :

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!

Answer

You can throw error from .catch(), substitute Promise.prototype.catch() for 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);
});

Comments