Skip to content

Instantly share code, notes, and snippets.

@jamesseanwright
Created September 16, 2017 09:02
Show Gist options
  • Save jamesseanwright/ec2172c7ecf8410542dd70cc2072332b to your computer and use it in GitHub Desktop.
Save jamesseanwright/ec2172c7ecf8410542dd70cc2072332b to your computer and use it in GitHub Desktop.
Handling Promise rejection within Express routes
'use strict';
const fetch = require('node-fetch');
const express = require('express');
const router = express.Router();
/* This function returns an inner function(i.e. a higher-order
* function) that will be invoked by Express when a particular
* path is request. This inner function will invoke the wrapped
* handler, and invoke Express' next function if the returned
* Promise is rejected. */
function createPromiseRoute(route) {
return (req, res, next) => route(req, res).catch(next);
}
function myRoute(req, res) {
return fetch('https://some-api')
.then(r => r.json())
.then(r => res.json(r));
}
router.get('/data', createPromiseRoute(myRoute));
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment