1 year ago

#364924

test-img

Alan Mayer

ES6 way to wrap every express controller in a try catch block

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.

javascript

ecmascript-6

composition

0 Answers

Your Answer

Accepted video resources