如何使用包装函数捕获node.js中的错误?

问题描述 投票:0回答:1

我正在使用

AsyncHandler
包装函数来捕获控制器和服务层中的错误。 我使用
next()
参数来引发错误,然后在我的全局错误处理程序中捕获它。 我的全局错误处理程序正在执行,但我的控制器也在返回,即使它在抛出错误后不应该返回任何内容。 我的控制器层:

const categoryCtrl = {
  create: asyncHandler( async (req, res, next) => {

    const data = await CategoryService.createCategory("", 4, next)

   return  successResponse({res, data:data, msg:"Category created Successfully"})

  }),
  getAll: async (req, res, next) => {},
  getById: async (req, res, next) => {},
  delete: async (req, res, next) => {},
  update: async (req, res, next) => {},
};

我的服务层:

const categoryService = {
  createCategory: async (data, x, next) => {
  
      if (data === "") {
        console.log("condition");
        const err = new CustomError(404, "Wrong input");
        return next(err);
      } else {
        return data;
      }

  },
};

我的 asyncHandler :

const asyncHandler = (func) => {
  return  (req, res, next) => {
    try {
       func(req, res, next)

    } catch (error) {
      next(error)

    }


  };
};

我的

successReponse

module.exports  = ({res, msg, data}) => {

    return res.status(200).json({msg:msg, data: data})

}

我尝试使用

throw
,但我试图避免在控制器层和服务层中出现 try-catch 块,并仅使用
next()
参数引发错误。

javascript node.js express node-modules
1个回答
0
投票

看起来

asyncHandler
没有正确处理其内部操作的异步性质。具体来说,它不会等待它包装的
func
完成。 您可以修改您的
asyncHandler
以正确处理这样的异步函数

const asyncHandler = (func) => {
  return (req, res, next) => {
    func(req, res, next).catch(next);
  };
};

这个 asyncHandler 现在显式处理 func 返回的 Promise。

© www.soinside.com 2019 - 2024. All rights reserved.