1

I am cleaning my code and moving from callback hell to async/await and try/catch but I still want to make my code DRY as I have too many routes and performing same try catch in every request. What could be the best way to handle this?

this my example code in one of the GET route.

router.get('/customer', async (req, res, next) => {
    try {
        const customer = await Customer.find({}).populate('buisness').exec();
        return res.status(200).json({
            result: customer
        });
    } catch (e) {
        return next(e);
    }
});

now if I repeat same thing on every route it is not following DRY code. what could be the best?

1 Answer 1

5
const errorHandlerMiddleware = async (req, res, next) =>  {
  try {
    await next();
  } catch (err) {
    // handle the error here
  }
};
router.use(errorHandlerMiddleware);

router.get('/customer', async (req, res, next) => {
  const customer = await Customer.find({}).populate('buisness').exec();
  return res.status(200).json({
    result: customer
  });
});

use errorHandlerMiddleware before all your routes, this middleware will catch every exception that is thrown from your routes. now every time there is an exception in your route it will be caught in the middleware

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.