Node.js 当i处理错误时,NodeJ抛出未处理的PromisejectionWarning
当用户有意输入错误的objectId时,我想处理该错误,但当我在函数检查objectId中压缩该错误时,我得到了以下错误:UnhandledPromisejectionWarning:错误:无效的\u ID 功能检查obejctID:Node.js 当i处理错误时,NodeJ抛出未处理的PromisejectionWarning,node.js,express,mongoose,Node.js,Express,Mongoose,当用户有意输入错误的objectId时,我想处理该错误,但当我在函数检查objectId中压缩该错误时,我得到了以下错误:UnhandledPromisejectionWarning:错误:无效的\u ID 功能检查obejctID: function checkObjectId(...ids) { ids.forEach(id => { const objectId = mongoose.Types.ObjectId.isValid(id); if
function checkObjectId(...ids) {
ids.forEach(id => {
const objectId = mongoose.Types.ObjectId.isValid(id);
if (!objectId) throw new MyError('INVALID_ID',404);
});
}
服务:
static async updateAuthor(_id, content) {
checkObjectId(_id);
const author = await Author.findByIdAndUpdate(_id, content, { new: true });
if (!author) throw new MyError('CAN_NOT_FIND_AUTHOR', 404);
return author;
}
路由器:
routerAuthor.put('/:_id',async (req, res) => {
AuthorService.updateAuthor(req.params._id,req.body)
.then(author => res.send({success : true, author}))
.catch(res.onError);
});
app.use((req, res, next) => {
res.onError = function(error) {
const body = { success: false, message: error.message };
if (!error.statusCode) console.log(error);
res.status(error.statusCode || 500).send(body);
};
next();
});
尝试使用Try-catch:
static async updateAuthor(_id, content) {
try {
checkObjectId(_id);
const author = await Author.findByIdAndUpdate(_id, content, { new: true });
if (!author) throw new MyError('CAN_NOT_FIND_AUTHOR', 404);
return author;
} catch (e) {
throw new Error(e);
}
}
你能提供你的代码片段吗?看起来你的
checkObjectId
定义像异步函数checkObjectId