Problem with async error handling with Express

Issue

I am trying to avoid the try catch block in route handlers. I am trying to catch the error in the following manner:

const catchAsync = (fn) => {

    // why this function does not have access to req,res,next?
    // I am passing async(req,res,next) as an argument, hence
    // req,res,next should be known to this function

    fn(req, res, next).catch((err) => next(err));
  
};

and then in the route handler:

exports.createTour = catchAsync(async (req, res, next) => {
  const newTour = await Tour.create(req.body);
  res.status(201).json({
    status: "success",
    data: {
      tour: newTour,
    },
  });
});

Now the problem is that, I don’t understand why the function fn(req,res,next) inside the catchAsync function block, does not have access to (req,res,next) when called ?
All I understand is that I am passing async(req,res,next) as an argument to catchAsync function. Hence when the function gets called inside the catchAsync block, it should have access to req,res,next

Solution

req,res,next are parameters of the fn function. These are variables that are local to the function’s own execution context. When you call a function, you’re supposed to provide values for these parameter variables. You cannot access those variables themselves, as they don’t exist yet before the call is getting executed.

Answered By – trincot

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published