【问题标题】:catch(err) giving error but do not return object data in async function in node express jscatch(err) 给出错误但不在节点 express js 的异步函数中返回对象数据
【发布时间】: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


【解决方案1】:

尝试用Promise.resolve包装返回值:

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

   }
}

【讨论】:

  • 您在 Express 中注册了全局路由错误处理程序吗?
猜你喜欢
  • 2021-10-29
  • 2021-07-04
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
相关资源
最近更新 更多