From 0b4274e8cc9e9a2c5a06f35fbf456ccfcebc55a5 Mon Sep 17 00:00:00 2001 From: chimurai <655241+chimurai@users.noreply.github.com> Date: Sun, 6 Oct 2024 16:58:31 +0000 Subject: [PATCH] fix(filter): handle errors --- CHANGELOG.md | 1 + package.json | 2 +- src/http-proxy-middleware.ts | 9 +++++++-- test/e2e/http-proxy-middleware.spec.ts | 28 ++++++++++++++++++++++++++ 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3969f00a..de9c1b0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## [v2.0.7](https://github.com/chimurai/http-proxy-middleware/releases/tag/v2.0.7) - ci(github actions): add publish.yml +- fix(filter): handle errors ## [v2.0.6](https://github.com/chimurai/http-proxy-middleware/releases/tag/v2.0.6) diff --git a/package.json b/package.json index 4c8e3743..00398625 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "http-proxy-middleware", - "version": "2.0.7-beta.0", + "version": "2.0.7-beta.1", "description": "The one-liner node.js proxy middleware for connect, express and browser-sync", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/http-proxy-middleware.ts b/src/http-proxy-middleware.ts index b93ae92f..a241cd68 100644 --- a/src/http-proxy-middleware.ts +++ b/src/http-proxy-middleware.ts @@ -109,8 +109,13 @@ export class HttpProxyMiddleware { * @return {Boolean} */ private shouldProxy = (context, req: Request): boolean => { - const path = req.originalUrl || req.url; - return contextMatcher.match(context, path, req); + try { + const path = req.originalUrl || req.url; + return contextMatcher.match(context, path, req); + } catch (error) { + this.logger.error(error); + return false; + } }; /** diff --git a/test/e2e/http-proxy-middleware.spec.ts b/test/e2e/http-proxy-middleware.spec.ts index 4685cc07..15355e91 100644 --- a/test/e2e/http-proxy-middleware.spec.ts +++ b/test/e2e/http-proxy-middleware.spec.ts @@ -153,6 +153,34 @@ describe('E2E http-proxy-middleware', () => { const response = await agent.get(`/api/b/c/d`).expect(404); expect(response.status).toBe(404); }); + + it('should not proxy when filter throws Error', async () => { + const myError = new Error('MY_ERROR'); + const filter = (path, req) => { + throw myError; + }; + + const logger = { + log: jest.fn(), + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; + + agent = request( + createApp( + createProxyMiddleware(filter, { + target: `http://localhost:${mockTargetServer.port}`, + logProvider: () => logger, + }) + ) + ); + + await mockTargetServer.get('/api/b/c/d').thenReply(200, 'HELLO WEB'); + const response = await agent.get(`/api/b/c/d`).expect(404); + expect(response.status).toBe(404); + expect(logger.error).toHaveBeenCalledWith(expect.objectContaining(myError)); + }); }); describe('multi path', () => {