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

2
  • Where/how are you using createTour? Is it being used in an express route? Commented Sep 7, 2022 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 Commented Sep 7, 2022 at 10:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.