处理快递的错误响应

ema*_*man 4 mongoose express reactjs redux

我正在尝试从中发送错误响应并表达api调用,当用户添加非唯一类别或根本没有类别时,api调用会出错。我能够将类别保存到数据库并发送回适当的响应。我不确定我在快递中使用的是正确的回复方法。

表示:

exports.addCategory = (req, res, next) => {
  var category = new Category(req.body);
  category.save().then(doc => {
    res.send(doc);
  }).catch(err => {
    res.send({message:'Category must be unique!'});
  });

}
Run Code Online (Sandbox Code Playgroud)

反应

export function addCategoryName( name ){
  return (dispatch) => {
    const dbPost = axios.post('/api/add-category', {name:name});
    dbPost.then(result => {
      console.log("result = ", result);
      dispatch({
        type: type.ADD_CATEGORY_NAME,
        payload: result.data
      });
    }).catch(err => {
      console.log("CATCH = ", err);
      // dispatch({
      //   type: type.ADD_CATEGORY_NAME_ERROR,
      //   payload: err.message
      // });
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的响应直接进入dbPost.then(result => {而不是catch。所以我尝试了

Express response

res.status(err.statusCode || 500).json({message:msg});
Run Code Online (Sandbox Code Playgroud)

This gave me:

CATCH =  Error: Request failed with status code 500
    at createError (createError.js:15)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)
Run Code Online (Sandbox Code Playgroud)

All i'm trying to do is respond with an error message from express and for my axios promise to catch it as an error. But I can't seem to get to the error message. Is there something I'm missing in express as a response for this.

ema*_*man 6

所以事实证明,这不是我的明确回应,而是我需要添加console.log(“ CATCH =”,err.response);的事实。在我的axios中承诺会做出反应。我缺少响应对象。我不知道我需要那个。

对于完整的代码,以防其他人遇到相同的问题。

反应:

export function addCategoryName( name ){
  return (dispatch) => {
    const dbPost = axios.post('/api/add-category', {name:name});
    dbPost.then(result => {
      console.log("result = ", result);
      dispatch({
        type: type.ADD_CATEGORY_NAME,
        payload: result.data
      });
    }).catch(err => {
      console.log("CATCH = ", err.response);
       dispatch({
         type: type.ADD_CATEGORY_NAME_ERROR,
         payload: error.response.data.error
       });
    });
  }
}
Run Code Online (Sandbox Code Playgroud)