Created
March 30, 2019 13:04
-
-
Save olehcambel/418edc9ed259aa95e7d71bcc3020b748 to your computer and use it in GitHub Desktop.
async error handling with express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { asyncWrap } from './async-wrap'; | |
| const app = express(); | |
| asyncWrap(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Request, Response, NextFunction } from 'express'; | |
| const Layer = require('express/lib/router/layer'); | |
| export const asyncWrap = (): void => { | |
| Layer.prototype.handle_request = async function handle( | |
| req: Request, | |
| res: Response, | |
| next: NextFunction, | |
| ) { | |
| const fn = this.handle; | |
| // not a standard request handler | |
| if (fn.length > 3) return next(); | |
| try { | |
| await fn(req, res, next); | |
| } catch (err) { | |
| next(err); | |
| } | |
| }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment