I am attempting to circumvent the try catch block in route handlers by handling errors differently:
const catchAsync = (fn) => {
// Why doesn't this function have access to req, res, next?
// I'm passing async(req, res, next) as an argument, so
// req, res, and next should be recognized by 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,
},
});
});
The issue now is that I can't figure out why the fn(req, res, next)
function inside the catchAsync
block does not have access to (req, res, next)
when called.
All I know is that I am passing async(req, res, next)
as an argument to the catchAsync
function. Therefore, when the function is invoked within the catchAsync
block, it should have access to req, res, next
.