diff --git a/lib/loaders/express.loader.ts b/lib/loaders/express.loader.ts index 99c51d99..6fbcb8e6 100644 --- a/lib/loaders/express.loader.ts +++ b/lib/loaders/express.loader.ts @@ -71,14 +71,14 @@ export class ExpressLoader extends AbstractLoader { } app.use((err: any, req: any, _res: any, next: Function) => { + if (err instanceof HttpException) { + throw err; + } + if (isRouteExcluded(req, options.exclude)) { const method = httpAdapter.getRequestMethod(req); const url = httpAdapter.getRequestUrl(req); return next(new NotFoundException(`Cannot ${method} ${url}`)); - } - - if (err instanceof HttpException) { - throw err; } else if (err?.message?.includes('ENOENT')) { throw new NotFoundException(err.message); } else if (err?.code === 'ENOENT') { diff --git a/tests/e2e/express-adapter.e2e-spec.ts b/tests/e2e/express-adapter.e2e-spec.ts index 822713fc..179bcc1f 100644 --- a/tests/e2e/express-adapter.e2e-spec.ts +++ b/tests/e2e/express-adapter.e2e-spec.ts @@ -1,4 +1,4 @@ -import { INestApplication } from '@nestjs/common'; +import { INestApplication, PayloadTooLargeException } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { Server } from 'net'; import request from 'supertest'; @@ -156,4 +156,32 @@ describe('Express adapter', () => { await app.close(); }); }); + + describe('when error happens in the previous middleware', () => { + beforeAll(async () => { + app = await NestFactory.create(AppModule.withDefaults(), { + logger: new NoopLogger() + }); + + app.use((_req, _res, next) => { + next(new PayloadTooLargeException()); + }); + + app.setGlobalPrefix('api'); + + server = app.getHttpServer(); + await app.init(); + }); + + it('should return 413', async () => { + return request(server) + .get('/api') + .expect(413) + .expect(/Payload Too Large/); + }); + + afterAll(async () => { + await app.close(); + }); + }); });