[英]Why unhandled promise rejection
無論我在哪里使用郵遞員向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))
})
})
我錯過了什么?
您需要添加一個catch()
拒絕處理)到findOne()
來處理發生的任何錯誤/拒絕findOne()
來自unhandledrejection的 Node.js 流程文檔:
'unhandledRejection' 事件在 Promise 被拒絕並且在事件循環的一個回合內沒有錯誤處理程序附加到 Promise 時發出。 使用 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);
});
}
);
基本上只要你有then()
來處理任何錯誤拒絕,就添加一個catch()
。
希望這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.