NestJS
Exception Handling
Handling errors and custom exceptions in NestJS.
Custom Exception Filter: Create a filter to catch and format specific exceptions globally or locally.
http-exception.filter.ts
TypeScript
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
Using the Custom Filter: Apply the custom filter globally in your main application file.
main.ts
TypeScript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './http-exception.filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Apply the custom exception filter globally
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);
}
bootstrap();