0

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

Saptaparnee
  • 25
  • 1
  • 1
  • 5
  • Where/how are you using `createTour`? Is it being used in an express route? – Nick Parsons Sep 07 '22 at 10:52
  • I think what you're after is similar to the second code block from the bottom of this answer: [Handling errors in express async middleware](https://stackoverflow.com/a/51391081) – Nick Parsons Sep 07 '22 at 10:55

1 Answers1

2

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.

trincot
  • 317,000
  • 35
  • 244
  • 286