简体   繁体   English

为什么未处理的承诺拒绝

[英]Why unhandled promise rejection

Wherever I am making a post request using postman to localhost:5000/api/profile/experience I am getting these warning无论我在哪里使用邮递员向localhost:5000/api/profile/experience发出帖子请求,我都会收到这些警告

UnhandledPromiseRejectionWarning: ValidationError: Profile validation failed: experience.0.title: Path `title` is required., experience.0.company: Path `company` is required., experience.0.from: Path `from` is required.

and also I am not getting error message saying that title, company, from values are required eventhough I have not field those field.而且我也没有收到错误消息,指出即使我没有填写这些字段,也需要标题、公司和值。 Here my validation js file这是我的验证js文件

const Validator = require('validator');
const isEmpty = require('./is-empty');


module.exports = function validateExperienceInput(data){
    let errors = {};


    data.title = !isEmpty(data.title) ? data.title : '';
    data.company = !isEmpty(data.company) ? data.company : '';
    data.from = !isEmpty(data.from) ? data.from : '';


    if(Validator.isEmpty(data.title)){
        errors.title = 'Title field is required'
    }


    if(Validator.isEmpty(data.company)){
        errors.company = 'company field is required'
    }



    if(Validator.isEmpty(data.from)){
        errors.from = 'From field is required'
    }

return {
        errors, 
        isValid: isEmpty(errors)
    }
}

Here is the router file这是路由器文件

router.post('/experience', passport.authenticate('jwt',{session: false}), (req,res) => {

    const {errors, isValid} = validateExperienceInput(req.body);

    Profile.findOne({user:req.user.id})
            .then(profile => {
                const newExp = {
                    title: req.body.title,
                    company: req.body.company,
                    location: req.body.location,
                    from: req.body.from,
                    to: req.body.to,
                    current: req.body.current,
                    description: req.body.description
                }

                // Add to exp array 

                profile.experience.unshift(newExp)
                profile.save().then(profile => res.json(profile))
            })
})

What am I missing?我错过了什么?

You need to add a catch() (rejection handler) to findOne() to handle any errors/rejections occurring from findOne() .您需要添加一个catch()拒绝处理)到findOne()来处理发生的任何错误/拒绝findOne() From the Node.js Process documentation for unhandledrejection :来自unhandledrejection的 Node.js 流程文档:

The 'unhandledRejection' event is emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop. 'unhandledRejection' 事件在 Promise 被拒绝并且在事件循环的一个回合内没有错误处理程序附加到 Promise 时发出。 When programming with Promises, exceptions are encapsulated as "rejected promises".使用 Promise 进行编程时,异常被封装为“被拒绝的承诺”。 Rejections can be caught and handled using promise.catch() and are propagated through a Promise chain.可以使用 promise.catch() 捕获和处理拒绝,并通过 Promise 链传播。 The 'unhandledRejection' event is useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled. 'unhandledRejection' 事件可用于检测和跟踪被拒绝的承诺,其拒绝尚未处理。

router.post(
  "/experience",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const { errors, isValid } = validateExperienceInput(req.body);

    Profile.findOne({ user: req.user.id })
      .then(profile => {
        const newExp = {
          title: req.body.title,
          company: req.body.company,
          location: req.body.location,
          from: req.body.from,
          to: req.body.to,
          current: req.body.current,
          description: req.body.description
        };

        // Add to exp array

        profile.experience.unshift(newExp);
        profile.save().then(profile => res.json(profile));
      })
      .catch(err => {
        // do something with error here such send error message or logging
        // res.json(err);
      });
  }
);

Basically add a catch() anytime you have a then() to handle any errors rejections.基本上只要你有then()来处理任何错误拒绝,就添加一个catch()

Hopefully that helps!希望这有帮助!

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

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