node.jsexpressexpress-4

Express middleware - add promise rejection handlers


I have the following simplified middleware function:

router.put('/', function (req, res, next) {

  const data = req.body;
  const q = req.parsedFilterParam;
  const opts = req.parsedQueryOpts;

  ResponseCtrl.update(q, data, opts)
  .then(stdPromiseResp(res))
  .catch(next);
});

I want to add some ability to catch errors to the middleware, just to save some code, something like this:

router.put('/', function (req, res, next) {

  const data = req.body;
  const q = req.parsedFilterParam;
  const opts = req.parsedQueryOpts;

  return ResponseCtrl.update(q, data, opts)
  .then(stdPromiseResp(res));

});

so we now return the promise in the middleware function, and we can forgo the catch block.

so internally, it might look like this now:

nextMiddlewareFn(req,res,next);

just looking to change it to:

const v = nextMiddlewareFn(req,res,next);
if(v && typeof v.catch === 'function'){
   v.catch(next);
});

does anyone know how to do this with Express?


Solution

  • Use express promise router.

    var router = new ExpressPromiseRouter();
    
    router.get('/foo', function(req, res) {
      return somethingPromisey();
    });
    // or...
    router.get('/bar', async function(req, res) {
      await somethingPromisey();
    });
    
    app.use(router);
    

    PS: There's no need to be afraid of async/await on performance grounds. There is no appreciable difference vs regular functions with promises.