在存储库中,当findById时,我使用以下代码处理不匹配的_id
:
getById: function (id) {
return new Promise(function (resolve, reject) {
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
// Yes, it's a valid ObjectId, proceed with
findById call.
console.log('Not match id');
reject('Not found');
return;
}
propertyModel.findById(id).exec(function (err, item) {
if (err) {
reject(err);
}
resolve(item);
});
});
},
在控制器中:
getListProperty: function (req, res, next) {
let query = req.query;
try {
propertyRepo.getList(query).then(item => {
return res.status(200).json(item);
})
} catch (err) {
console.log(err);
return res.status(400).json(err);
}
}
当找不到_id
时,我无法处理错误。我该如何处理?
答案 0 :(得分:0)
请尝试声明.catch以处理诺言中的错误
getById: function (id) {
return new Promise(function (resolve, reject) {
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
// Yes, it's a valid ObjectId, proceed withfindByIdcall.
console.log('Not match id');
reject('Not found');
return;
}
propertyModel.findById(id).exec(function (err, item) {
if (err) {
reject(err);
}
resolve(item);
})
.catch((error) => {
reject(error)
})
});
},