Skip to content

Commit 3589b96

Browse files
author
maxbronnikov10
committed
refactor(core,express,fastify): HTTP adapter error mapping
1 parent f2d8543 commit 3589b96

File tree

7 files changed

+116
-45
lines changed

7 files changed

+116
-45
lines changed

packages/core/adapters/http-adapter.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,10 @@ export abstract class AbstractHttpAdapter<
143143
return path;
144144
}
145145

146+
public mapException(error: unknown): unknown {
147+
return error;
148+
}
149+
146150
abstract close();
147151
abstract initHttpServer(options: NestApplicationOptions);
148152
abstract useStaticAssets(...args: any[]);

packages/core/router/routes-resolver.ts

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ export class RoutesResolver implements Resolver {
162162
res: TResponse,
163163
next: Function,
164164
) => {
165-
throw this.mapExternalException(err);
165+
throw this.container.getHttpAdapterRef().mapException(err);
166166
};
167167
const handler = this.routerExceptionsFilter.create(
168168
{},
@@ -178,18 +178,6 @@ export class RoutesResolver implements Resolver {
178178
);
179179
}
180180

181-
public mapExternalException(err: any) {
182-
switch (true) {
183-
// SyntaxError is thrown by Express body-parser when given invalid JSON (#422, #430)
184-
// URIError is thrown by Express when given a path parameter with an invalid percentage
185-
// encoding, e.g. '%FF' (#8915)
186-
case err instanceof SyntaxError || err instanceof URIError:
187-
return new BadRequestException(err.message);
188-
default:
189-
return err;
190-
}
191-
}
192-
193181
private getModulePathMetadata(metatype: Type<unknown>): string | undefined {
194182
const modulesContainer = this.container.getModules();
195183
const modulePath = Reflect.getMetadata(

packages/core/test/router/routes-resolver.spec.ts

Lines changed: 1 addition & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
1-
import {
2-
BadRequestException,
3-
Module,
4-
Post,
5-
VersioningType,
6-
} from '@nestjs/common';
1+
import { Module, Post, VersioningType } from '@nestjs/common';
72
import { MODULE_PATH } from '@nestjs/common/constants';
83
import { expect } from 'chai';
94
import * as sinon from 'sinon';
@@ -318,32 +313,6 @@ describe('RoutesResolver', () => {
318313
});
319314
});
320315

321-
describe('mapExternalExceptions', () => {
322-
describe('when exception prototype is', () => {
323-
describe('SyntaxError', () => {
324-
it('should map to BadRequestException', () => {
325-
const err = new SyntaxError();
326-
const outputErr = routesResolver.mapExternalException(err);
327-
expect(outputErr).to.be.instanceof(BadRequestException);
328-
});
329-
});
330-
describe('URIError', () => {
331-
it('should map to BadRequestException', () => {
332-
const err = new URIError();
333-
const outputErr = routesResolver.mapExternalException(err);
334-
expect(outputErr).to.be.instanceof(BadRequestException);
335-
});
336-
});
337-
describe('other', () => {
338-
it('should behave as an identity', () => {
339-
const err = new Error();
340-
const outputErr = routesResolver.mapExternalException(err);
341-
expect(outputErr).to.be.eql(err);
342-
});
343-
});
344-
});
345-
});
346-
347316
describe('registerNotFoundHandler', () => {
348317
it('should register not found handler', () => {
349318
routesResolver.registerNotFoundHandler();

packages/platform-express/adapters/express-adapter.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
BadRequestException,
23
HttpStatus,
34
InternalServerErrorException,
45
Logger,
@@ -448,6 +449,18 @@ export class ExpressAdapter extends AbstractHttpAdapter<
448449
throw new Error('Unsupported versioning options');
449450
}
450451

452+
public mapException(error: unknown): unknown {
453+
switch (true) {
454+
// SyntaxError is thrown by Express body-parser when given invalid JSON (#422, #430)
455+
// URIError is thrown by Express when given a path parameter with an invalid percentage
456+
// encoding, e.g. '%FF' (#8915)
457+
case error instanceof SyntaxError || error instanceof URIError:
458+
return new BadRequestException(error.message);
459+
default:
460+
return error;
461+
}
462+
}
463+
451464
private trackOpenConnections() {
452465
this.httpServer.on('connection', (socket: Duplex) => {
453466
this.openConnections.add(socket);

packages/platform-express/test/adapters/express-adapter.spec.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1+
import { BadRequestException } from '@nestjs/common';
12
import { ExpressAdapter } from '@nestjs/platform-express';
23
import { expect } from 'chai';
34
import * as express from 'express';
45
import * as sinon from 'sinon';
56

67
describe('ExpressAdapter', () => {
8+
let expressAdapter: ExpressAdapter;
9+
10+
beforeEach(() => {
11+
expressAdapter = new ExpressAdapter();
12+
});
13+
714
afterEach(() => sinon.restore());
815

916
describe('registerParserMiddleware', () => {
@@ -43,4 +50,24 @@ describe('ExpressAdapter', () => {
4350
expect(useSpy.called).to.be.false;
4451
});
4552
});
53+
54+
describe('mapException', () => {
55+
it('should map URIError with status code to BadRequestException', () => {
56+
const error = new URIError();
57+
const result = expressAdapter.mapException(error) as BadRequestException;
58+
expect(result).to.be.instanceOf(BadRequestException);
59+
});
60+
61+
it('should map SyntaxError with status code to BadRequestException', () => {
62+
const error = new SyntaxError();
63+
const result = expressAdapter.mapException(error) as BadRequestException;
64+
expect(result).to.be.instanceOf(BadRequestException);
65+
});
66+
67+
it('should return error if it is not handler Error', () => {
68+
const error = new Error('Test error');
69+
const result = expressAdapter.mapException(error);
70+
expect(result).to.equal(error);
71+
});
72+
});
4673
});

packages/platform-fastify/adapters/fastify-adapter.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
/* eslint-disable @typescript-eslint/no-floating-promises */
22
import { FastifyCorsOptions } from '@fastify/cors';
33
import {
4+
BadRequestException,
5+
HttpException,
46
HttpStatus,
57
Logger,
68
RawBodyRequest,
@@ -18,6 +20,7 @@ import { LegacyRouteConverter } from '@nestjs/core/router/legacy-route-converter
1820
import {
1921
FastifyBaseLogger,
2022
FastifyBodyParser,
23+
FastifyError,
2124
FastifyInstance,
2225
FastifyListenOptions,
2326
FastifyPluginAsync,
@@ -670,6 +673,25 @@ export class FastifyAdapter<
670673
return 'fastify';
671674
}
672675

676+
public mapException(error: unknown): unknown {
677+
if (this.isHttpFastifyError(error)) {
678+
return new HttpException(error.message, error.statusCode);
679+
}
680+
681+
return error;
682+
}
683+
684+
private isHttpFastifyError(
685+
error: unknown,
686+
): error is FastifyError & { statusCode: number } {
687+
// condition based on this code - https://github.com/fastify/fastify-error/blob/d669b150a82968322f9f7be992b2f6b463272de3/index.js#L22
688+
return (
689+
error instanceof Error &&
690+
error.name === 'FastifyError' &&
691+
(error as FastifyError).statusCode !== undefined
692+
);
693+
}
694+
673695
protected registerWithPrefix(
674696
factory:
675697
| FastifyPluginCallback<any>
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { FastifyAdapter } from '../../adapters/fastify-adapter';
2+
import { expect } from 'chai';
3+
import { createError } from '@fastify/error';
4+
import { HttpException } from '@nestjs/common';
5+
6+
describe('FastifyAdapter', () => {
7+
let fastifyAdapter: FastifyAdapter;
8+
9+
beforeEach(() => {
10+
fastifyAdapter = new FastifyAdapter();
11+
});
12+
13+
describe('mapException', () => {
14+
it('should map FastifyError with status code to HttpException', () => {
15+
const FastifyErrorCls = createError(
16+
'FST_ERR_CTP_INVALID_MEDIA_TYPE',
17+
'Unsupported Media Type: %s',
18+
415,
19+
);
20+
const error = new FastifyErrorCls();
21+
22+
const result = fastifyAdapter.mapException(error) as HttpException;
23+
24+
expect(result).to.be.instanceOf(HttpException);
25+
expect(result.message).to.equal(error.message);
26+
expect(result.getStatus()).to.equal(415);
27+
});
28+
29+
it('should return FastifyError without user status code to Internal Server Error HttpException', () => {
30+
const FastifyErrorCls = createError(
31+
'FST_WITHOUT_STATUS_CODE',
32+
'Error without status code',
33+
);
34+
const error = new FastifyErrorCls();
35+
36+
const result = fastifyAdapter.mapException(error) as HttpException;
37+
expect(result).to.be.instanceOf(HttpException);
38+
expect(result.message).to.equal(error.message);
39+
expect(result.getStatus()).to.equal(500);
40+
});
41+
42+
it('should return error if it is not FastifyError', () => {
43+
const error = new Error('Test error');
44+
const result = fastifyAdapter.mapException(error);
45+
expect(result).to.equal(error);
46+
});
47+
});
48+
});

0 commit comments

Comments
 (0)