Skip to content

Commit

Permalink
Normalize Fastify errors
Browse files Browse the repository at this point in the history
This also suppresses error logs for log4shell attempts
  • Loading branch information
CarsonF committed Oct 28, 2024
1 parent f7957ca commit 12e27f1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/core/exception/exception.normalizer.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// eslint-disable-next-line no-restricted-imports,@seedcompany/no-restricted-imports
import * as Nest from '@nestjs/common';
import * as Fastify from 'fastify';
import { InputException, ServerException } from '~/common';
import { ConstraintError } from '../database';
import { ExceptionNormalizer } from './exception.normalizer';
Expand All @@ -10,6 +11,23 @@ describe('ExceptionNormalizer', () => {
const orig = sut.normalize.bind(sut);
sut.normalize = (...args) => JSON.parse(JSON.stringify(orig(...args)));

describe('Fastify', () => {
it('Client', () => {
const ex = new Fastify.errorCodes.FST_ERR_CTP_BODY_TOO_LARGE();
const res = sut.normalize({ ex });
expect(res.message).toEqual('Request body is too large');
expect(res.code).toEqual('FST_ERR_CTP_BODY_TOO_LARGE');
expect(res.codes).toEqual(['FST_ERR_CTP_BODY_TOO_LARGE', 'Client']);
});
it('Server', () => {
const ex = new Fastify.errorCodes.FST_ERR_HOOK_INVALID_TYPE();
const res = sut.normalize({ ex });
expect(res.message).toEqual('The hook name must be a string');
expect(res.code).toEqual('FST_ERR_HOOK_INVALID_TYPE');
expect(res.codes).toEqual(['FST_ERR_HOOK_INVALID_TYPE', 'Server']);
});
});

describe('HttpException', () => {
it('simple', () => {
const ex = new Nest.NotFoundException();
Expand Down
9 changes: 9 additions & 0 deletions src/core/exception/exception.normalizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,15 @@ export class ExceptionNormalizer {
return { codes: ['GraphQL', 'Server'] };
}

// Fastify convention
if ('statusCode' in ex && typeof ex.statusCode === 'number') {
const codes = [
'code' in ex && typeof ex.code === 'string' ? ex.code : undefined,
ex.statusCode < 500 ? 'Client' : 'Server',
];
return { codes };
}

// Fallback to generic Error
return { codes: ['Server'] };
}
Expand Down

0 comments on commit 12e27f1

Please sign in to comment.