Skip to content

Commit 4334527

Browse files
Add exception filters for error handling
1 parent 2f1692f commit 4334527

File tree

4 files changed

+48
-16
lines changed

4 files changed

+48
-16
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { ArgumentsHost, Catch, ExceptionFilter, Logger } from '@nestjs/common';
2+
import { Response } from 'express';
3+
@Catch()
4+
export class AllExceptionFilter implements ExceptionFilter {
5+
catch(exception: unknown, host: ArgumentsHost) {
6+
Logger.debug(exception['message'], 'MongooseValidationFilter');
7+
8+
const ctx = host.switchToHttp();
9+
const response = ctx.getResponse<Response>();
10+
const status = 500;
11+
12+
return response.status(status).json({
13+
statusCode: status,
14+
message: exception['message'] || exception['name'] || 'Internal server error',
15+
});
16+
}
17+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { ArgumentsHost, Catch, ExceptionFilter, Logger } from '@nestjs/common';
2+
import { ValidationException } from '~/_common/errors/ValidationException';
3+
import { Response } from 'express';
4+
5+
@Catch(ValidationException)
6+
export class IdentitiesValidationFilter implements ExceptionFilter {
7+
catch(exception: ValidationException, host: ArgumentsHost) {
8+
const ctx = host.switchToHttp();
9+
const response = ctx.getResponse<Response>();
10+
const status = exception.getStatus();
11+
12+
Logger.debug(exception['message'], 'IdentitiesValidationFilter');
13+
14+
return response.status(status).json({
15+
statusCode: status,
16+
message: exception.message,
17+
validations: exception.getValidations(),
18+
});
19+
}
20+
}

src/_common/filters/mongoose-validation.filter.ts

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,15 @@
1-
import {
2-
ArgumentsHost,
3-
Catch,
4-
ExceptionFilter,
5-
HttpException,
6-
HttpStatus,
7-
Logger,
8-
} from '@nestjs/common';
1+
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';
92
import { Request, Response } from 'express';
103
import { Error } from 'mongoose';
114
import { ValidationError } from 'class-validator';
125

136
@Catch(Error.ValidationError, Error.CastError, ValidationError)
147
export class MongooseValidationFilter implements ExceptionFilter {
15-
public catch(
16-
exception: Error.ValidationError | Error.CastError | ValidationError,
17-
host: ArgumentsHost,
18-
) {
8+
public catch(exception: Error.ValidationError | Error.CastError | ValidationError, host: ArgumentsHost) {
199
const ctx = host.switchToHttp();
2010
const request = ctx.getRequest<Request>();
2111
const response = ctx.getResponse<Response>();
12+
2213
Logger.debug(exception['message'], 'MongooseValidationFilter');
2314
const debug = {};
2415
if (process.env.NODE_ENV !== 'production' && request.query['debug']) {
@@ -47,8 +38,7 @@ export class MongooseValidationFilter implements ExceptionFilter {
4738
if (err.errors[key]['constraints']) {
4839
Object.keys(err.errors[key]['constraints']).forEach((ckey) => {
4940
const property = err.errors[key]['property'];
50-
validations[`${key}.${property}`] =
51-
err.errors[key]['constraints'][ckey];
41+
validations[`${key}.${property}`] = err.errors[key]['constraints'][ckey];
5242
});
5343
continue;
5444
}

src/main.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { NestFactory } from '@nestjs/core';
22
import { AppModule } from './app.module';
33
import configInstance from './config';
4-
import { LogLevel, Logger } from '@nestjs/common';
4+
import { All, LogLevel, Logger } from '@nestjs/common';
55
import { NestExpressApplication } from '@nestjs/platform-express';
66
import { utilities as nestWinstonModuleUtilities, WinstonModule } from 'nest-winston';
77
import { createLogger } from 'winston';
88
import * as winston from 'winston';
99
import 'winston-mongodb';
10-
import { appendFile } from 'fs';
10+
import { AllExceptionFilter } from './_common/filters/all-exception.filter';
11+
import { IdentitiesValidationFilter } from './_common/filters/identities-validation.filter';
12+
import { MongooseValidationFilter } from './_common/filters/mongoose-validation.filter';
1113

1214
declare const module: any;
1315
(async (): Promise<void> => {
@@ -61,9 +63,12 @@ declare const module: any;
6163
(await import('./swagger')).default(app);
6264
}
6365

66+
app.useGlobalFilters(new AllExceptionFilter(), new MongooseValidationFilter(), new IdentitiesValidationFilter());
67+
6468
await app.listen(3000, async (): Promise<void> => {
6569
Logger.log(`Application is running on port: ${process.env.PORT || 3000}`);
6670
});
71+
6772
if (module.hot) {
6873
module.hot.accept();
6974
module.hot.dispose((): Promise<void> => app.close());

0 commit comments

Comments
 (0)