Trung BìnhNestJS iconNestJS

Exception Filters trong NestJS là gì? Cách tạo global error handler.

Exception Filters bắt các exceptions được throw trong ứng dụng và format response lỗi. NestJS có built-in filter xử lý HttpException và các subclass của nó. Nếu exception không phải HttpException, NestJS trả về 500 Internal Server Error mặc định.

Custom global filter implement ExceptionFilter với method catch(exception, host). host.switchToHttp() lấy req/res. Trong filter có thể check instanceof HttpException để lấy status code, log lỗi, format response chuẩn với statusCode, message, timestamp, path.

Built-in HTTP exceptions: NotFoundException, BadRequestException, UnauthorizedException, ForbiddenException, ConflictException, InternalServerErrorException... Đăng ký global qua app.useGlobalFilters() hoặc preferred là { provide: APP_FILTER, useClass: ... } để hỗ trợ DI.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS