angularjs - 获取传递给 mongoose 中间件 next() 方法的错误消息到客户端 Controller

标签 angularjs node.js express mongoose mean-stack

我是 MEAN 堆栈的新手,所以请原谅我天真的问题,但我无法弄清楚如何将自定义错误消息从我的 Mongoose 预保存 Hook 中间件传递到我的 Angularjs Controller 。

我正在使用预保存 Hook 来检查文档之前是否已保存。如果有,那么我想取消保存尝试并更新文档。我使用 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();
    });
});

在我的客户端 Controller :

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 中间件(预保存 Hook )传递到 Angular Controller ?

最佳答案

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

错误.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();
    });
});

每次都会响应:

如果返回下一个(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 在下一个中间件中传递任何内容。

关于angularjs - 获取传递给 mongoose 中间件 next() 方法的错误消息到客户端 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45051309/

相关文章:

node.js - expressjs可以和nodejs net一起使用来监听TCP协议(protocol)吗

javascript - Angular 和 Jasmine - $scope 函数未定义

javascript - 在 karma、mocha 和 chai 中使用 $q 和 Angular 进行 promise

node.js - 如何通过 upstart 和 monit 支持多个 nodejs 服务?

json - Breeze Sequelize : get entities in the server + transaction

javascript - 是否有可能拥有一个 SEO 友好的 Express.js 网站?

javascript - 在两个 promise 在 angularJS 中解决后调用函数,一个使用另一个的结果

javascript - 将 DocRaptor Web 服务与 AngularJS 一起使用?

javascript - (带有 bodyParser 的 Node :5132) DeprecationWarning: `DEBUG_FD` is deprecated.

node.js - 获取外部文件并提供下载