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.

Built-in Exceptions

NestJS cung cấp sẵn các built-in exceptions:

Exception Filter Basics

Cách Tạo Exception Filter Đơn Giản

Sử dụng Exception Filter

Level Controller:
Level Method:
Global Level (trong main.ts):

ArgumentsHost - Truy Cập Context

ArgumentsHost cung cấp method để truy cập request/response objects:

Ví Dụ Exception Filters Thực Tế

1. HTTP Exception Filter

2. Validation Exception Filter

3. Database Exception Filter

4. All Exceptions Filter (Catch-All)

5. Custom Business Logic Exception Filter

6. Rate Limit Exception Filter

7. Authentication Exception Filter

8. Logging Exception Filter

Registering Exception Filters

Method-level

Class-level

Module-level (Provider)

Global-level

Custom Exception Classes

Sử dụng Custom Exceptions

Exception Filter Chain

Thứ tự xử lý: Từ trên xuống dưới, filter đầu tiên match sẽ handle exception.

Best Practices

1. Đặc Thù Hóa Exceptions

Sử dụng specific exceptions thay vì generic:

2. Consistent Error Response Format

3. Logging Errors

4. Tidak Leak Sensitive Information

5. Proper Status Codes

Complete Example

Kết Luận

Exception Filters là công cụ quan trọng để:
  • Xử lý exceptions một cách consistent
  • Tạo professional error responses
  • Logging và monitoring errors
  • Bảo vệ sensitive information
  • Cải thiện user experience
Sử dụng Exception Filters đúng cách giúp bạn xây dựng ứng dụng robust, maintainable, và user-friendly.