Node.js catch(err)给出错误,但不在node express js的异步函数中返回对象数据
我使用的是节点v10.19.0,我已经创建了异步函数(req){},它有try-catch块,如果发生错误,那么它会控制错误,但不能返回该错误 在routes.js中:Node.js catch(err)给出错误,但不在node express js的异步函数中返回对象数据,node.js,express,async-await,postman,try-catch,Node.js,Express,Async Await,Postman,Try Catch,我使用的是节点v10.19.0,我已经创建了异步函数(req){},它有try-catch块,如果发生错误,那么它会控制错误,但不能返回该错误 在routes.js中:router.post(“/somefunction”,middleware.somefunction) 在middleware.js中: module.exports.somefunction = async (req, res) => { var someFuncResponse = await service.s
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
}
}
当我在postman上点击这个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.
尝试使用承诺包装返回值。解决:
module.exports.someFunction = async function (req) {
try{
//some code which gives error
let response = { id:1 }
return Promise.resolve({ 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 Promise.resolve({ status: false, data: response }) //not returning this
}
}
演示如何在管线中使用此功能handler@Anatoly在routes.js中:router.post(“/somefunction”,middleware.somefunction);在middleware.js中:module.exports.somefunction=async(req,res)=>{var someFuncResponse=wait service.somefunction(req)res.send(someFuncResponse)}在service.js中:实际函数写入module.exports.somefunction=async function(req){definition}请你把所有这些都添加到问题中,并加上格式)@Anatoly done。请查查。尝试在Promise中包装两条路径的返回值。解决是否在Express中注册了全局路由错误处理程序?