Exception Filters trong NestJS
Exception Filters là một cơ chế để bắt và xử lý exceptions (ngoại lệ) trong ứng dụng NestJS. Chúng cho phép bạn kiểm soát chính xác cách exceptions được xử lý và trả về cho client, giúp tạo ra error responses một cách consistent và professional.
Khái Niệm Exception Filter
Exception Filter là một class implement interface ExceptionFilter<T>. Nó có một method catch() được gọi khi một exception được throw ra.
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { Response } from 'express';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
response.status(500).json({
statusCode: 500,
message: 'Internal server error',
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
Built-in Exceptions
NestJS cung cấp sẵn các built-in exceptions:
import {
BadRequestException,
UnauthorizedException,
ForbiddenException,
NotFoundException,
ConflictException,
InternalServerErrorException,
NotImplementedException,
BadGatewayException,
ServiceUnavailableException,
GatewayTimeoutException,
HttpException,
} from '@nestjs/common';
// Sử dụng built-in exceptions
throw new NotFoundException('User not found');
throw new UnauthorizedException('Invalid credentials');
throw new BadRequestException('Invalid input');
throw new ConflictException('User already exists');
throw new InternalServerErrorException('Database error');