Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(router): handle rejected promise in custom router #413

Merged
merged 2 commits into from Mar 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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