我有一个现有的 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!');
})
我的定义getActiveId
如下。
exports.getActiveId = id => axiosInstance
.get('/example')
.then(({ data }) => data)
.catch(er => er);
上面getActiveId
定义中的问题是每次catch的时候getActiveId
,执行落入上面端点定义的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)
如何修复此错误并绕过执行错误中间件?