首页 > 解决方案 > 为什么未处理的承诺拒绝

问题描述

无论我在哪里使用邮递员发出帖子请求,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.

而且我没有收到错误消息说标题,公司,来自值是必需的,即使我没有填写这些字段。这是我的验证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)
    }
}

这是路由器文件

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))
            })
})

我错过了什么?

标签: javascriptnode.jsmongodb

解决方案


您需要添加一个catch()(拒绝处理程序)来findOne()处理从findOne(). 来自unhandledrejection的 Node.js Process 文档:

每当一个 Promise 被拒绝并且在事件循环的一个轮次中没有错误处理程序附加到该 Promise 时,就会发出 'unhandledRejection' 事件。使用 Promises 进行编程时,异常被封装为“被拒绝的 Promise”。可以使用 promise.catch() 捕获和处理拒绝,并通过 Promise 链传播。'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);
      });
  }
);

基本上,catch()您可以随时添加一个then()来处理任何错误拒绝。

希望这会有所帮助!


推荐阅读