我的承诺的成功块总是执行,即使当我返回一个404

当用户使用不正确的电子邮件和密码login时,即使服务器返回了400,客户端承诺的成功块仍然会执行。

我正在使用Redux和React,所以我打电话给使用axios调用HTTP请求的动作创build器。 我需要帮助,理解为什么我没有正确处理错误,因为我的应用程序的其余部分的身份validationfunction,如注册,注销等,都performance出相同的方式,即使我从服务器返回400状态。

这里是我从我的组件调用login,成功块总是执行:

handleFormSubmit({ email, password }) { this.props.loginUser({ email, password }).then(() => { toastr.success("You are logged in!"); }).catch(() => { toastr.warning("Could not log in"); }) } 

这里是动作创build者“loginUser”,当我从服务器返回400时,该函数的成功块不会运行:

 export function loginUser({ email, password }) { return function(dispatch) { return axios.post(`/users/login`, { email, password }) .then(response => { dispatch({ type: AUTH_USER }); localStorage.setItem('token', response.headers['x-auth']); browserHistory.push('/feature'); }) .catch(() => { dispatch(authError('Incorrect email or password')); }); } } 

这里是路由“/用户/login”请注意,400的状态确实返回:

 app.post('/users/login', (req, res) => { var body = _.pick(req.body, ['email', 'password']); User.findByCredentials(body.email, body.password).then(user => { return user.generateAuthToken().then(token => { res.header('x-auth', token).send(user); }); }).catch(e => { res.status(400).send(); }); }); 

你的问题是,你误解了承诺条款是什么。

你可以认为,如果它只是一个拒绝处理程序的方式:

 .then(null, function(err) { // handle the error }) 

这意味着它只能处理来自promise链的最后一个未处理的错误,无论发生什么事,都可以继续进行链接。

例:

 new Promise((resolve, reject) => { setTimeout(() => reject(Error('After 1 sec')), 1000) }) .catch((err) => { console.log(`catch: ${err}`); return 5; }) .then((five) => { // this chains because the error was handled before in the chain console.log(`catch.then: ${five}`); // 5 }) .catch(() => { console.log('No error happened between this error handler and previous so this is not logged'); }); 

问题出在你的loginUser函数的catch处理程序中。 如果你想捕捉承诺链中的错误,你需要把这个错误放在catch块中。

  .catch(() => { dispatch(authError('Incorrect email or password')); throw Error('Incorrect email or password'); });