简体   繁体   English

在 router.js 上使用 promise 模拟错误处理

[英]Simulate error handling with promises on router.js

I am trying to save Sensor values to my mongodb database.我正在尝试将传感器值保存到我的 mongodb 数据库中。 I am using promise to do proper error handling.我正在使用 promise 进行正确的错误处理。 I am using then() and catch() but I guess I am not doing it right.我正在使用then()catch()但我想我做得不对。 I send a group Id so it checks if the group id exists then only it stores sensor information.我发送一个组 ID,以便它检查组 ID 是否存在,然后仅存储传感器信息。 Here is my code.这是我的代码。

router.post('/data/:group_id', function(req,res,next){
    var group_id = req.params.group_id;
    User.find({group_id : group_id}).then(function(user){
        var object_id = user[0]._id;
        var datas = req.body;
        var data = new Data({
           user : object_id,
            value: datas.value,
            valueString : datas.valueString,
            sensorStatus : datas.sensorStatus,
            timeStamp : new Date().toJSON()
        });
        data.save().then(function(data){
            res.send('Data Saved');
        });
    }).catch(function(e){
        if(e.code === undefined){
            res.send('Group id does not exist');
        }else{
            res.send(e);
        }
    });
});

if I send a group Id that does not exist it does say Group id does not exist, but if I send a wrong json data for saving my sensor information, there is no error but my postman-app which I am using to send information gets stuck.如果我发送一个不存在的组 ID,它确实说组 ID 不存在,但是如果我发送了错误的 json 数据来保存我的传感器信息,则没有错误,但是我用来发送信息的邮递员应用程序得到卡住。 Here is a error I purposely generated with a valid group ID.这是我故意使用有效组 ID 生成的错误。

I am new to this so need to understand how promise handles the error for first if the group_id cannot be found and second if the sensor json information is wrong.我对此很陌生,因此需要了解 Promise 如何在无法找到 group_id 时首先处理错误,然后在传感器 json 信息错误的情况下处理错误。

Sent to http://localhost:3000/api/data/3发送到http://localhost:3000/api/data/3

{
    "value1" : "79" ,
    "valueString" : "Small data",
     "sensorStatus" : "false"
}

Extra information User and Datas model.额外信息用户和数据模型。 Note( Dint add the require and export part)注意(请添加 require 和 export 部分)

var schema = new Schema({
    group_id : {type : Number, required: true},
    password : {type : String, default: null},
    project : {type : String , default : null}
});
var schema = new Schema({
    user: {type: Schema.Types.ObjectId, ref: 'User'},
    value :{type : Number , required : true} ,
    valueString : {type : String, required : true},
    sensorStatus : {type : Boolean , default : 0},
    timeStamp  : {type :String , required : true}
});

Right, you're falling to a common pitfall: Don't nest .then() clauses, instead, return Promises and chain:是的,您陷入了一个常见的陷阱:不要嵌套.then()子句,而是返回 Promise 和链:

Don't do不要做

foo().then(() => {
  bar().then(() => {
    baz();
  }
}

Return the Promise from inside of the .then() and chain, like so:.then()和链内部返回 Promise,如下所示:

foo()
  .then(() => { return bar(); })
  .then(() => { return baz(); });

Or the shorter version或者更短的版本

foo()
  .then(() => bar())
  .then(() => baz());

In your case:在你的情况下:

router.post('/data/:group_id', function(req,res,next){
  var group_id = req.params.group_id;
  User.find({group_id : group_id})
    .then(function(user){
      // bla bla bla
      return data.save();
    })
    .then(function(data){
      return res.send('Data Saved');
    });
    .catch(function(e){
      if(e.code === undefined){
          res.send('Group id does not exist');
      }else{
          res.send(e);
      }
    });
});

As a common rule: Always return or throw from a .then() handler.作为一个通用规则:始终从.then()处理程序返回抛出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM