Skip to content

[NESTJS] Setup Global Exception Filters #2

@abdegenius

Description

@abdegenius

📌 Task: [NESTJS] Setup Global Exception Filters

📝 Description

We need to implement a Global Exception Filter in our NestJS application to ensure consistent and centralized error handling across all modules. This will help improve maintainability, debuggability, and developer/user experience by standardizing how errors are caught and returned in HTTP responses.

🎯 Goals

  • Create a global exception filter that handles:

    • HttpException
    • UnauthorizedException, ForbiddenException, etc.
    • Unhandled exceptions (e.g., uncaught Error)
  • Format error responses consistently (e.g., including timestamp, path, status code, error message, etc.)

  • Ensure logging is done for critical exceptions (use NestJS logger or a custom logger if applicable)

  • Apply the global filter using app.useGlobalFilters() in the main bootstrap file

  • Optionally handle and log validation errors from class-validator and class-transformer

📁 Expected Folder/Files

  • src/common/filters/http-exception.filter.ts (suggested location)
  • main.ts (for global registration)

✅ Acceptance Criteria

  • A custom HttpExceptionFilter is created with support for multiple types of exceptions
  • The filter provides a standardized JSON response format
  • Errors are properly logged (e.g., using Logger.error)
  • The filter is registered globally in main.ts
  • Unit tests cover common exception scenarios
  • Integration test validates behavior on typical endpoints

🔧 Example Response Format

{
  "statusCode": 400,
  "timestamp": "2025-06-03T12:00:00.000Z",
  "path": "/api/example",
  "message": "Bad Request"
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions