【问题标题】:How do I unpack this error with Mongoose and Promisify?如何使用 Mongoose 和 Promisify 解压缩此错误?
【发布时间】:2016-04-18 06:48:23
【问题描述】:

我在 Mongoose 和 Promisify 中有这个

这是预保存条件 - 我检查是否有暂停(超时),如果一切正常,则添加一个

//check if there is a pause for this id
HonkSchema.pre('save', function(next) {
  var query  = Pause.where({ id: this.id }).findOneAsync()
    .then(function(res){
        if(res) {

          var e = new Error('Not 5 Minutes')
          next(e)
        }//else {
          next()
        //}
    })
    .catch(function(err){
      console.log(err)
      var err = new Error(err);
      next(err);
    })
});

//Add pause
HonkSchema.pre('save', function(next) {
  Pause.createAsync({id: this.id})
    .then(function(res){
      next()
    })
    .catch(function(err){
      console.log(err)
      var err = new Error(err);
      next(err);
    })
});

我这样新建一个

// Creates a new Honk in the DB
export function create(req, res) {
  Honk.createAsync(req.body)
    .then(responseWithResult(res, 201))
    .catch(handleError(res, 412));
}

handleError 就是这样做的

function handleError(res, statusCode) {
  statusCode = statusCode || 500;
  return function(err) {
    console.log(err)
    res.status(statusCode).send(JSON.stringify(err));
  };
}

上面的日志信息给出了这个

{ [Error: Not 5 Minutes] cause: [Error: Not 5 Minutes], isOperational: true }

但是给客户端的错误信息是这样的

{"cause":{},"isOperational":true}

所以我的问题是,如何向客户端发送有意义的消息?

【问题讨论】:

  • FWIW,Mongoose 已经支持 promises 开箱即用。另外,您想究竟返回给客户什么?一个文本字符串,一个 JSON 对象,...?
  • 我在想一个带有错误字段的 JSON 对象。我会拿出所有承诺的东西,看看进展如何

标签: node.js mongodb mongoose promise


【解决方案1】:

你可以这样使用:

return res.status(statusCode).send({ error : err.message });

【讨论】:

  • 我明白了。我认为所有的承诺都捆绑了结果,但它只是 Error 对象。谢谢
【解决方案2】:

我发现 findOne 查询中的错误 find more than one result 意味着它是操作错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2012-05-22
    相关资源
    最近更新 更多