From 3fa5b0d478f151576802dde7f78ed187e81fc3ae Mon Sep 17 00:00:00 2001 From: Brian Forbis Date: Fri, 13 Mar 2020 16:16:53 -0400 Subject: [PATCH] fix(router): handle rejected promise in custom router --- src/http-proxy-middleware.ts | 8 ++++++-- test/e2e/router.spec.ts | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/http-proxy-middleware.ts b/src/http-proxy-middleware.ts index 2874b6f1..208b90f2 100644 --- a/src/http-proxy-middleware.ts +++ b/src/http-proxy-middleware.ts @@ -49,8 +49,12 @@ export class HttpProxyMiddleware { next: express.NextFunction ) => { if (this.shouldProxy(this.config.context, req)) { - const activeProxyOptions = await this.prepareProxyRequest(req); - this.proxy.web(req, res, activeProxyOptions); + try { + const activeProxyOptions = await this.prepareProxyRequest(req); + this.proxy.web(req, res, activeProxyOptions); + } catch (err) { + next(err); + } } else { next(); } diff --git a/test/e2e/router.spec.ts b/test/e2e/router.spec.ts index bca9cae1..970e0af2 100644 --- a/test/e2e/router.spec.ts +++ b/test/e2e/router.spec.ts @@ -1,4 +1,5 @@ import { createProxyMiddleware, createApp, createAppWithPath } from './_utils'; +import { ErrorRequestHandler } from 'express'; import * as request from 'supertest'; import { getLocal, generateCACertificate, Mockttp } from 'mockttp'; @@ -100,6 +101,27 @@ describe('E2E router', () => { expect(response.text).toBe('C'); }); + it('should handle promise rejection in router', async () => { + const app = createApp( + createProxyMiddleware({ + target: 'https://localhost:6001', + secure: false, + changeOrigin: true, + router: async req => { + throw new Error('An error thrown in the router'); + } + }) + ); + const errorHandler: ErrorRequestHandler = (err: Error, req, res, next) => { + res.status(502).send(err.message); + }; + app.use(errorHandler); + + const agent = request(app); + const response = await agent.get('/api').expect(502); + expect(response.text).toBe('An error thrown in the router'); + }); + it('missing a : will cause it to use http', async () => { const app = createApp( createProxyMiddleware({