Advertisement
nodejsdeveloperskh

try-catch wrapper middleware

Aug 8th, 2021
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const middlewareHandler = fn => (req, res, next) =>
  2.     Promise
  3.         .resolve(fn(req, res, next))
  4.         .catch((error) => {
  5.             logger.error('error', { meta: { ...error }})
  6.             next();
  7.         });
  8.  
  9. router
  10.     .route('/')
  11.     .post(middlewareHandler(xController))
  12.  
  13. function xController(req, res, next) {
  14.   /* Write a lot of code without any try catch block */
  15.   const { xId } = req.params;
  16.   const x = await xRpository(xId);
  17.  
  18.   res.json({ success: true, x });
  19. }
  20.  
  21. async function xRepository(xId) {
  22.   const x = await xModel.findById(xId);
  23.   // ...
  24.  
  25.   return x;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement