【发布时间】:2021-01-18 09:16:36
【问题描述】:
我正在使用节点 v10.19.0 并且我创建了异步函数 (req) {} 如果发生错误,它会尝试 catch 块,然后它会控制台错误但无法返回该错误。
在 routes.js 中:router.post("/somefunction", middleware.somefunction);
在 middleware.js 中:
module.exports.somefunction = async (req, res) => {
var someFuncResponse = await service.someFunction(req)
res.send(someFuncResponse)
}
在 service.js 中:
module.exports.someFunction = async function (req) {
try{
//some code which gives error
let response = { id:1 }
return { status: true, data: response }
}catch(error){
// catches the error
let response = { id:2 }
console.log(error) // get print correctly
console.log(response) // get print correctly
return { status: false, data: response } //not returning this
}
}
当我在邮递员上点击这个 api 时,我收到“无法得到响应”消息。
我也在控制台上低于味精:
(node:55009) 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: 1)
(node:55009) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
【问题讨论】:
-
展示你如何在路由处理器中使用这个函数
-
@Anatoly 在 routes.js: router.post("/somefunction", middleware.somefunction);在 middleware.js 中:module.exports.somefunction = async (req, res) => { var someFuncResponse = await service.someFunction(req) res.send(someFuncResponse) } 在 service.js 中:实际编写的函数 module.exports.someFunction = 异步函数 (req) {定义}
-
您能否将所有这些添加到问题中并带有格式)
-
@Anatoly 完成。请检查。
-
嗯。尝试将两个路径的返回值包装在
Promise.resolve
标签: node.js express async-await postman try-catch