Skip to content

Commit

Permalink
feat: handle errors in async middlewares
Browse files Browse the repository at this point in the history
errors thrown in async middlewares would usually lead to
unhandled promise rejections and wouldn't trigger the express
error handler.

this change catches exceptions in async middlewares and forwards
them to the express error handler by calling `next`

Co-authored-by: Björn Brauer <[email protected]>
Co-authored-by: Jonas Holland <[email protected]>
  • Loading branch information
3 people authored and hops-release-bot[bot] committed Sep 16, 2021
1 parent 05b6096 commit c89f3b8
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions packages/express/lib/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,25 @@ const isPlainObject = require('is-plain-obj');

const { Router } = express;

function wrapMiddleware(middleware, domain) {
return Object.defineProperty(
domain.bind((...args) => {
try {
const maybePromise = middleware(...args);
if (maybePromise && typeof maybePromise.catch === 'function') {
maybePromise.catch(args[args.length - 1]);
}
} catch (e) {
args[args.length - 1](e);
}
}),
'length',
{
value: middleware.length,
}
);
}

module.exports = (mode, { configureServer, handleError }) => {
const phases = ['initial', 'files', 'parse', 'routes', 'final'].reduce(
(result, key) => [...result, `pre${key}`, key, `post${key}`],
Expand All @@ -36,16 +55,12 @@ module.exports = (mode, { configureServer, handleError }) => {
const handlers = [].concat(handler);
container[method](
path,
...handlers.map((handler) => domain.bind(handler))
...handlers.map((handler) => wrapMiddleware(handler, domain))
);
} else {
const middlewares = [].concat(middleware);
container.use(
...middlewares.map((middleware) =>
Object.defineProperty(domain.bind(middleware), 'length', {
value: middleware.length,
})
)
...middlewares.map((middleware) => wrapMiddleware(middleware, domain))
);
}
});
Expand Down

0 comments on commit c89f3b8

Please sign in to comment.