即使我的代码中有 catch 部分,我也收到未处理的承诺拒绝错误



我只是在尝试处理来自post请求的数据。我正在 catch 部分处理数据,以便将其记录在控制台中,但仍然收到错误未处理的承诺拒绝。

router.post('/', (req, res, next) => {
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price
});
product
.save()
.then(result => {
console.log(result);
});
.catch(err => console.log(err));
res.status(201).json({
message: 'Handling post request to /products.',
createdProduct: product
});
});

有时数据库库会这样做。我以前也有过类似的经历。您可以使用全局错误处理程序并查看发生了什么。

process.on('unhandledRejection', function(reason, p){
//call handler here
});

这可能会为这个问题提供更多的线索。

最新更新