0

I have an express app that has controllers that look like this:

export const createObject = async (req, res) => {
  try {
    ...do stuff
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
export const updateObject = async (req, res) => {
  try {
    ...do stuff
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
... etc

is there a fancy ES6 way to wrap every one of those calls in the try-catch block? I want to do something like:

const tryCatchWrapper = (f, res, code) => {
  return () => {
    try {
      return f.apply(this, arguments);
    } catch (e) {
      res.status(code).json(e);
    }
  };
};
export const createObject = tryCatchWrapper(async (req, res) => {
    ...do stuff
  }
}, res, 500);

but I'm not quite sure how to construct/compose this.

Alan Mayer
  • 79
  • 6
  • 1
    That `tryCatchWrapper` you've shown **is** written in ES6 arrow function syntax already. What else do you want? – Bergi Apr 01 '22 at 18:18
  • Does [this](https://stackoverflow.com/questions/41349331/is-there-a-way-to-wrap-an-await-async-try-catch-block-to-every-function/) answer your question? It uses ES8 though. – Bergi Apr 01 '22 at 18:20
  • @Bergi I think I am close, but how do I pass the res into the try catch wrapper so that it can handle the response? my code above doesn't actually work since the res is not available when passed in to the wrapper – Alan Mayer Apr 03 '22 at 11:03
  • 1
    You don't pass it into `tryCatchWrapper`. It's a parameter to the returned function - use `return (req, res, next) => { try { await f(req, res, next) …`. – Bergi Apr 03 '22 at 12:44
  • Btw `.apply(this, arguments)` doesn't work with an arrow function – Bergi Apr 03 '22 at 12:45
  • removing the arrow functions and using named parameters as you mentioned worked @Bergi – Alan Mayer Apr 05 '22 at 10:38

0 Answers0