{"id":26796326,"url":"https://github.com/webxsid/nest-exception","last_synced_at":"2025-03-29T18:18:18.421Z","repository":{"id":277746369,"uuid":"933370347","full_name":"webxsid/nest-exception","owner":"webxsid","description":null,"archived":false,"fork":false,"pushed_at":"2025-03-08T12:32:48.000Z","size":117,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-08T13:30:31.053Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/webxsid.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-15T19:42:46.000Z","updated_at":"2025-03-08T12:32:51.000Z","dependencies_parsed_at":"2025-02-15T20:29:42.152Z","dependency_job_id":"c09a4b01-3bda-4ffc-8cd8-bba6897e94e6","html_url":"https://github.com/webxsid/nest-exception","commit_stats":null,"previous_names":["webxsid/nest-exception"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webxsid%2Fnest-exception","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webxsid%2Fnest-exception/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webxsid%2Fnest-exception/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webxsid%2Fnest-exception/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/webxsid","download_url":"https://codeload.github.com/webxsid/nest-exception/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246223308,"owners_count":20743168,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-29T18:18:17.812Z","updated_at":"2025-03-29T18:18:18.415Z","avatar_url":"https://github.com/webxsid.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @webxsid/nest-exception\n\n![Coverage](https://codecov.io/gh/webxsid/nest-exception/branch/main/graph/badge.svg)\n[![Test \u0026 Coverage](https://github.com/webxsid/nest-exception/actions/workflows/test-covergare.yml/badge.svg)](https://github.com/webxsid/nest-exception/actions/workflows/test-covergare.yml)\n[![NPM Version](https://img.shields.io/npm/v/@webxsid/nest-exception)](https://www.npmjs.com/package/@webxsid/nest-exception)\n[![License](https://img.shields.io/github/license/webxsid/nest-exception)](LICENSE)\n\nA centralized exception handling module for NestJS applications. It provides structured error management, logging, and automatic exception handling.\n\n## Features\n\n- **Centralized Error Registry**: Define and manage application errors easily.\n- **Automatic Error Handling**: Custom `AppException` class integrates seamlessly.\n- **Flexible Error Registration**: Predefine errors in the module or register dynamically.\n- **Extendable Error Handling**: Customize error handling with `ExceptionFilter`.\n- **Stack Trace (Development Mode)**: Automatically captures stack trace for debugging.\n- **Seamless Integration**: Just import the module and start using it.\n\n## Installation\n\nInstall the package using npm or yarn:\n\n```bash\n$ npm install @webxsid/nest-exception\n# or\n$ yarn add @webxsid/nest-exception\n```\n\n## Usage\n\n### Importing and Setting Up the Module\n\n- Import the `AppExceptionModule` in the root module using `forRoot` or `forRootAsync`:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { AppExceptionModule } from '@webxsid/nest-exception';\n\n@Module({\n    imports: [AppExceptionModule.forRoot({\n        isDev: process.env.NODE_ENV === 'development',\n        errors: [\n            { code: 'E001', message: 'User not found' },\n            { code: 'E002', message: 'Invalid credentials' },\n        ],\n        logger: LoggerService // Any implementation of LoggerService\n    })],\n})\nexport class AppModule {}\n```\n\n#### Async Configuration\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { AppExceptionModule } from '@webxsid/nest-exception';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n    imports: [\n        ConfigModule.forRoot(),\n        AppExceptionModule.forRootAsync({\n            imports: [ConfigModule],\n            useFactory: (configService: ConfigService) =\u003e ({\n                isDev: configService.get('NODE_ENV') === 'development',\n                errors: [\n                    { code: 'E001', message: 'User not found' },\n                    { code: 'E002', message: 'Invalid credentials' },\n                ],\n                logger: LoggerService // Any implementation of LoggerService\n            }),\n            inject: [ConfigService]\n        })\n    ],\n})\nexport class AppModule {}\n```\n\n### Registering the Global Exception Filter\n\nTo apply the `AppExceptionFilter` globally in your application, register it in your root module (`AppModule`):\n\n```typescript\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { APP_FILTER } from '@nestjs/core';\nimport { AppExceptionFilter } from '@webxsid/nest-exception';\n\n@Module({\n    providers: [\n        {\n            provide: APP_FILTER,\n            useClass: AppExceptionFilter,\n        },\n    ],\n})\nexport class AppModule {}\n```\n\n## Error Management\n\n### Registering Errors in the Module\n\nErrors can be pre-registered in the module configuration:\n\n```typescript\nimports: [\n    AppExceptionModule.forRoot({\n        errors: [\n            { code: 'E001', message: 'User not found' },\n            { code: 'E002', message: 'Invalid credentials' },\n        ]\n    })\n]\n```\n\n### Registering Errors Dynamically\n\n- Use the `ExceptionRegistry` service to register errors at runtime:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { ExceptionRegistry } from '@webxsid/nest-exception';\n\n@Injectable()\nexport class AppService {\n    constructor(private readonly exceptionRegistry: ExceptionRegistry) {}\n\n    registerErrors() {\n        this.exceptionRegistry.registerError({ code: 'E003', message: 'Invalid request' });\n    }\n}\n```\n\n### Extending the Exception Handler\n\n- Use the `ExceptionHandlerService` to customize error handling for specific exceptions:\n\n```typescript\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { ExceptionHandlerService } from '@webxsid/nest-exception';\nimport { ArgumentsHost, HttpStatus } from '@nestjs/common';\n\n@Injectable()\nexport class MongoErrorHandler implements OnModuleInit {\n    constructor(private readonly exceptionHandlerService: ExceptionHandlerService) {}\n\n    onModuleInit() {\n        this.exceptionHandlerService.register(MongoError, (exception: MongoError, host: ArgumentsHost) =\u003e {\n            const response = host.switchToHttp().getResponse();\n            response.status(HttpStatus.BAD_REQUEST).json({\n                statusCode: HttpStatus.BAD_REQUEST,\n                errorCode: 'MONGO_ERROR',\n                message: exception.message,\n                timestamp: new Date().toISOString(),\n            });\n        });\n    }\n}\n```\n\n- Add the handler class to the module providers:\n\n```typescript\n@Module({\n    imports: [AppExceptionModule.forRoot(/*...*/)],\n    providers: [MongoErrorHandler]\n})\nexport class AppModule {}\n```\n\n### Throwing Custom Exceptions\n\n- Use the `AppException` class to throw predefined errors:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { AppException } from '@webxsid/nest-exception';\n\n@Injectable()\nexport class AppService {\n    async getUser(id: string) {\n        const user = await this.userService.findById(id);\n        if (!user) {\n            throw new AppException('E001');\n        }\n        return user;\n    }\n}\n```\n\n## How It Works\n\nThe AppException class simplifies error handling by checking if the provided error code exists in the Exception Registry. Here’s how it behaves in different scenarios:\n\n### 1. ✅ Passing a Registered Error Code\n\nIf the error code exists in the registry (either pre-registered in the module or added dynamically), AppException will:\n•\tRetrieve the corresponding error message and status code.\n•\tConstruct a structured HTTP response with the correct status, message, and code.\n\n```typescript\nthrow new AppException('E001'); \n```\n\n**Output:**\n```json\n{\n    \"statusCode\": 400,\n    \"errorCode\": \"E001\",\n    \"message\": \"User not found\",\n    \"timestamp\": \"2021-09-01T12:00:00.000Z\"\n}\n```\n_(Assuming the error code 'E001' is registered with the message 'User not found' and status code 400)_\n\n### 2. ❌ Passing an Unregistered Error Code or String\n\nIf the error code is not found in the registry, AppException will:\n•\tThrow an internal server error with the default message and status code.\n•\tLog the error using the provided logger service.\n\n```typescript\nthrow new AppException('Something went wrong'); \n```\n\n**Output:**\n```json\n{\n    \"statusCode\": 500,\n    \"errorCode\": \"UNKNOWN_ERROR\",\n    \"message\": \"Internal server error\",\n    \"timestamp\": \"2021-09-01T12:00:00.000Z\"\n}\n```\n\n#### 🛠️ Development Mode (Stack Trace)\n\nIf **development mode** (isDev: true) is enabled, AppException will also include a stack trace for easier debugging:\n\n```json\n{\n    \"statusCode\": 500,\n    \"errorCode\": \"UNKNOWN_ERROR\",\n    \"message\": \"Internal server error\",\n    \"timestamp\": \"2021-09-01T12:00:00.000Z\",\n    \"stack\": \"Error: Internal server error\\n    at AppService.getUser (/app/app.service.ts:12:13)\\n    at processTicksAndRejections (internal/process/task_queues.js:93:5)\"\n}\n```\n\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Acknowledgements\n\n- [NestJS](https://nestjs.com/)\n- [TypeScript](https://www.typescriptlang.org/)\n- [Jest](https://jestjs.io/)\n- [ESLint](https://eslint.org/)\n\n## Author\n\n[Siddharth Mittal](https://webxsid.com/)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebxsid%2Fnest-exception","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebxsid%2Fnest-exception","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebxsid%2Fnest-exception/lists"}