【发布时间】:2021-08-17 14:29:48
【问题描述】:
我正在使用 express 创建一个 REST API,遵循 this article 的架构。 简而言之,路由器正在调用控制器。
这是一个调用示例:
router.get('/', ModelsController.getModels)
到目前为止,这项工作还不错,现在,我正在使用 Boom 改进错误处理。
我想使用 this article 中的包装器,但由于我不使用 TS 并且我不熟悉 Promises,所以我正在努力解决。
这是包装器:
exports.enhanceHandler = async function (handler) {
return async function (req, res, next) {
try {
const result = await handler(req, res);
if (result instanceof Error && Boom.isBoom(result)) {
res.status(result.output.statusCode).send(formatBoomPayload(result));
}
} catch (error) {
// now log errors to your errors reporting software
if (process.env.NODE_ENV !== "production" && (error.stack || error.message)) {
res.status(500).send(error.stack || error.message);
} else {
res.status(500).send(Boom.internal().output.payload);
}
}
next();
}
}
我正在尝试在我的路由器中调用它,如下所示:
router.get('/handler', enhanceHandler(ModelsController.getModels))
但是,我遇到了这个错误:
Error: Route.get() requires a callback function but got a [object Promise]
我能做什么?我需要解决承诺吗?修改 enhanceHandler 让它返回一个函数而不是一个承诺?
【问题讨论】:
-
使用
async关键字存在冲突。如果你有next参数,你应该使用所有回调 -
我添加了 async 因为 await 仅在 async 函数中有效。你能告诉我更多关于如何使用所有回调吗?
-
从
exports.enhanceHandler = async function (handler)中删除async关键字
标签: javascript node.js express