Skip to content

Commit 514c08b

Browse files
bforbischimurai
andauthored
fix(router): handle rejected promise in custom router (#413)
Co-authored-by: Brian Forbis <[email protected]> Co-authored-by: chimurai <[email protected]>
1 parent cb64266 commit 514c08b

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/http-proxy-middleware.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,12 @@ export class HttpProxyMiddleware {
4949
next: express.NextFunction
5050
) => {
5151
if (this.shouldProxy(this.config.context, req)) {
52-
const activeProxyOptions = await this.prepareProxyRequest(req);
53-
this.proxy.web(req, res, activeProxyOptions);
52+
try {
53+
const activeProxyOptions = await this.prepareProxyRequest(req);
54+
this.proxy.web(req, res, activeProxyOptions);
55+
} catch (err) {
56+
next(err);
57+
}
5458
} else {
5559
next();
5660
}

test/e2e/router.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createProxyMiddleware, createApp, createAppWithPath } from './_utils';
2+
import { ErrorRequestHandler } from 'express';
23
import * as request from 'supertest';
34
import { getLocal, generateCACertificate, Mockttp } from 'mockttp';
45

@@ -100,6 +101,27 @@ describe('E2E router', () => {
100101
expect(response.text).toBe('C');
101102
});
102103

104+
it('should handle promise rejection in router', async () => {
105+
const app = createApp(
106+
createProxyMiddleware({
107+
target: 'https://localhost:6001',
108+
secure: false,
109+
changeOrigin: true,
110+
router: async req => {
111+
throw new Error('An error thrown in the router');
112+
}
113+
})
114+
);
115+
const errorHandler: ErrorRequestHandler = (err: Error, req, res, next) => {
116+
res.status(502).send(err.message);
117+
};
118+
app.use(errorHandler);
119+
120+
const agent = request(app);
121+
const response = await agent.get('/api').expect(502);
122+
expect(response.text).toBe('An error thrown in the router');
123+
});
124+
103125
it('missing a : will cause it to use http', async () => {
104126
const app = createApp(
105127
createProxyMiddleware({

0 commit comments

Comments
 (0)