Skip to content

Commit

Permalink
fix(router): handle rejected promise in custom router (#413)
Browse files Browse the repository at this point in the history
Co-authored-by: Brian Forbis <bforbis@athenahealth.com>
Co-authored-by: chimurai <655241+chimurai@users.noreply.github.com>
  • Loading branch information
3 people committed Mar 14, 2020
1 parent cb64266 commit 514c08b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/http-proxy-middleware.ts
Expand Up @@ -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();
}
Expand Down
22 changes: 22 additions & 0 deletions 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';

Expand Down Expand Up @@ -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({
Expand Down

0 comments on commit 514c08b

Please sign in to comment.