获取传递给mongoose middleware next()方法的错误消息到客户端控制器

时间:2017-07-12 07:37:59

标签: angularjs node.js express mongoose mean-stack

我是MEAN堆栈的新手,所以请原谅我天真的问题,但是我还没弄清楚如何将我的Mongoose预保存挂钩中间件中的自定义错误消息传递给我的Angularjs控制器。

我使用预保存挂钩来检查之前是否保存过文档。如果有,那么我想取消保存尝试,而不是更新文档。我使用next(new Error('Error message'))方法来阻止save操作。以下是我的代码:

在我的后端:

VoteSchema.pre('save',function(next){
  var self = this;
  self.constructor.findOneAndUpdate(
    {'choice._id':self.choice._id},
    {$inc:{'choice.count':1}},
    {new:true},
    function(err,doc){
      if(err) return next(err);
      if(doc!==null){

        //I want to be able to pass a type like this {x:1, y:2}
        //to my angular controller from here. How do I do this?

        return next(new Error("Canceled save attempt!")); //this cancels the save
      } 
      return next();
    });
});

在我的客户控制器上:

vote.$save(function (response) {
      console.log(response);
    },
    function (errorResponse) {

      //I want to get my custom type from the pre-save 
      //middleware hook here which was equals to {x:1, y:2}
      //or at least the message "Canceled save attempt!"
      //Note that I checked the 'errorResponse' object but
      //it isn't anywhere there

      console.log(errorResponse);
    }
  );

换句话说,如何将自定义对象从mongoose中间件(预保存挂钩)传递给Angular控制器?

1 个答案:

答案 0 :(得分:0)

我在我的项目中做了什么,我创建了一个error.js文件并且还创建了许多可能的错误,当需要发送时我只需要我的error.js并发送错误,如下面的代码:

<强> error.js:

var errors = {};
var util = require('util');

/**
 * Used to create errors
 * @Param {Number} httpCode - http response code
 * @Param {String} message - Error message
 */
function ApiError(httpCode, httpMessage, description) {
    this.httpCode = httpCode;
    this.httpMessage = httpMessage;
    this.description = description;
    this.details = null;
}

// inherit the Error class
util.inherits(ApiError, Error);

// exporting error Object
module.exports = errors;

errors.ApiError = ApiError;

/**
 * Sends httpCode and message to user
 * @Param {Response} res - http response
 */
ApiError.prototype.send = function (res) {
    res.status(this.httpCode);
    res.json({ httpCode: this.httpCode, httpMessage: this.httpMessage, description: this.description, details: this.details })
}

ApiError.prototype.withDetails = function (details) {
    this.details = details;
    return this;
};

errors.not_registeration = new ApiError(404, 'NOT_REGISTERATION',
    'User not registered with this email/mobile.');


errors.invalid_login = new ApiError(400, 'INVALID_LOGIN',
    'Login credentials do not match any registered user.');

您可以使用我已创建的代码创建自己的错误。

如何在我的文件中使用错误:

var errors = require('../../library/errors');
.....
.....
.....
VoteSchema.pre('save',function(next){
  var self = this;
  self.constructor.findOneAndUpdate(
    {'choice._id':self.choice._id},
    {$inc:{'choice.count':1}},
    {new:true},
    function(err,doc){
      if(err) return next(err);
      if(doc!==null){

        return next(errors.not_registeration)  // Here  i am sending errors.
        or
        return next(errors.invalid_input.withDetails("This  is extra details"));

      } 
      return next();
    });
});

每次都会有回复:

如果返回next(errors.not_registeration) -

 {
        "httpCode": 404,
        "httpMessage": "NOT_REGISTERATION",
        "description": "User not registered with this email/mobile.",
        "details": null
    }

如果返回next(errors.invalid_input.withDetails(“这是额外的详细信息”)) -

{
    "httpCode": 400,
    "httpMessage": "INVALID_INPUT",
    "description": "The request input is not as expected by API. Please provide valid input.",
    "details": "This  is extra details"
}

** 据我所知,您希望将数据传递给下一个中间件。 然后,您可以在当前的中间件中执行此操作:

 res.locals.result={ X:1,Y:1};

在下一个中间件中,您可以像这样得到X,Y:console.log(res.locals.result); 您可以使用res.locals传递下一个中间件中的任何内容。