【发布时间】:2021-12-11 21:05:52
【问题描述】:
我有一个现有的 Node Express 应用程序并希望更好地改进错误处理。我当前的路由端点定义如下,
app.get('/example/getActiveId', async (req, res, next) => {
// Some code to fetch some details from request and do some validations
try {
const result = await api.getActiveId(id);
res.json({ success: true, result }); // I am getting this response in all the time.
} catch (err) {
console.log('getActiveId', err)
console.error(err);
res.json({ success: false });
}
});
另外,我在所有路由路径的最后定义了错误中间件。
// error handler middleware
app.use((error, req, res, next) => {
console.log('in Error middleware')
console.error(error.stack);
res.status(500).send(error.message || 'Something Broke!');
})
我对@987654323@的定义如下。
exports.getActiveId = id => axiosInstance
.get('/example')
.then(({ data }) => data)
.catch(er => er);
上面getActiveId定义的问题是每次getActiveId的catch,执行落入上面端点定义的try块。我希望执行应该进入 catch 块端点定义函数。这样我就可以调用next(err) 调用默认的快速错误处理中间件。
所以我尝试了以下样机代码来模拟相同的承诺拒绝。
exports.getActiveId = id => {
const __mockPromise = () => {
return new Promise((resolve, reject) => {
reject('Problem in getActiveId')
})
}
return new Promise((resolve, reject) => {
__mockPromise().then(({ data }) => resolve(data)).catch(er => { console.log('in catch....'); reject(er) })
});
}
我希望上面的函数会进入终点函数定义的catch块。
但这次我收到以下错误,
in catch....
(node:32897) UnhandledPromiseRejectionWarning: Problem in getActiveId
(node:32897) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
如何修复此错误并绕过执行到错误中间件?
【问题讨论】:
标签: node.js express exception unhandled-exception unhandled-promise-rejection