Skip to content

Instantly share code, notes, and snippets.

@hongphuc5497
Created January 13, 2023 07:37
Show Gist options
  • Save hongphuc5497/2525ab38ba4e02e6cd8acad11d36bacb to your computer and use it in GitHub Desktop.
Save hongphuc5497/2525ab38ba4e02e6cd8acad11d36bacb to your computer and use it in GitHub Desktop.
Build reusable Try Catch Wrapper in ExpressJS
/**
* It takes a function as an argument, and returns a function that will call the original function, and
* if it throws an error, it will call the next function in the middleware chain
* @param req - The request object
* @param res - The response object
* @param next - The next function in the middleware chain.
* @returns A function that takes a function as an argument and returns the result of that function.
*/
const wrapper = (req, res, next) => async (func) => {
try {
// eslint-disable-next-line no-undef
return await func.apply(this, arguments);
} catch (err) {
return next(err);
}
};
/**
* It takes a function as an argument, and returns a function that calls the argument function, and if
* it throws an error, it calls the next function with the error
* @param func - The function that you want to wrap.
*/
const alternativeWrapper = (func) => async (req, res, next) => {
try {
await func(req, res);
} catch (err) {
next(err);
}
};
// Example
// First approach
const list = (req, res, next) => {
const tryCatchWrapper = wrapper(req, res, next);
tryCatchWrapper(async () => {
const result = await businessFunc();
res.status(200).json(result);
});
};
// Second approach
const list = alternativeWrapper(async (req, res) => {
const result = await businessFunc();
res.status(200).json(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment