DEV Community

Kazi Abdur Rakib
Kazi Abdur Rakib

Posted on

Avoid try-catch repetition , use catchAsync

Avoid try-catch repetition , use catchAsync

Image description

===>>> RequestHandler
const createStudent: RequestHandler = async (req, res, next) => {
Enter fullscreen mode Exit fullscreen mode
//===> old system
const getAllStudents: RequestHandler = catchAsync(async (req, res, next) => {
  try {
    const result = await StudentServices.getAllStudentsFromBD();
    sendResponse(res, {
      statusCode: httpStatus.OK,
      success: true,
      message: 'getAllStudents is are retrived successgully',
      data: result,
    });
  } catch (err) {
    next(err);
  }
});

//=======================================

//===> new formula
const catchAsync = (asyncFn: RequestHandler) => {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(asyncFn(req, res, next)).catch((err) => next(err));
  };
};

const getAllStudents = catchAsync(async (req, res, next) => {
    const result = await StudentServices.getAllStudentsFromBD();
    sendResponse(res, {
      statusCode: httpStatus.OK,
      success: true,
      message: 'getAllStudents is are retrived successgully',
      data: result,
    });
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)