npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@webxsid/nest-exception

v1.0.2

Published

A centralized exception handling module for NestJS applications. It provides structured error management, logging, and automatic exception handling.

Readme

@webxsid/nest-exception

Coverage Test & Coverage NPM Version License

A centralized exception handling module for NestJS applications. It provides structured error management, logging, and automatic exception handling.

Features

  • Centralized Error Registry: Define and manage application errors easily.
  • Automatic Error Handling: Custom AppException class integrates seamlessly.
  • Flexible Error Registration: Predefine errors in the module or register dynamically.
  • Extendable Error Handling: Customize error handling with ExceptionFilter.
  • Stack Trace (Development Mode): Automatically captures stack trace for debugging.
  • Seamless Integration: Just import the module and start using it.

Installation

Install the package using npm or yarn:

$ npm install @webxsid/nest-exception
# or
$ yarn add @webxsid/nest-exception

Usage

Importing and Setting Up the Module

  • Import the AppExceptionModule in the root module using forRoot or forRootAsync:
import { Module } from '@nestjs/common';
import { AppExceptionModule } from '@webxsid/nest-exception';

@Module({
    imports: [AppExceptionModule.forRoot({
        isDev: process.env.NODE_ENV === 'development',
        errors: [
            { code: 'E001', message: 'User not found' },
            { code: 'E002', message: 'Invalid credentials' },
        ],
        logger: LoggerService // Any implementation of LoggerService
    })],
})
export class AppModule {}

Async Configuration

import { Module } from '@nestjs/common';
import { AppExceptionModule } from '@webxsid/nest-exception';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
    imports: [
        ConfigModule.forRoot(),
        AppExceptionModule.forRootAsync({
            imports: [ConfigModule],
            useFactory: (configService: ConfigService) => ({
                isDev: configService.get('NODE_ENV') === 'development',
                errors: [
                    { code: 'E001', message: 'User not found' },
                    { code: 'E002', message: 'Invalid credentials' },
                ],
                logger: LoggerService // Any implementation of LoggerService
            }),
            inject: [ConfigService]
        })
    ],
})
export class AppModule {}

Registering the Global Exception Filter

To apply the AppExceptionFilter globally in your application, register it in your root module (AppModule):

// app.module.ts
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { AppExceptionFilter } from '@webxsid/nest-exception';

@Module({
    providers: [
        {
            provide: APP_FILTER,
            useClass: AppExceptionFilter,
        },
    ],
})
export class AppModule {}

Error Management

Registering Errors in the Module

Errors can be pre-registered in the module configuration:

imports: [
    AppExceptionModule.forRoot({
        errors: [
            { code: 'E001', message: 'User not found' },
            { code: 'E002', message: 'Invalid credentials' },
        ]
    })
]

Registering Errors Dynamically

  • Use the ExceptionRegistry service to register errors at runtime:
import { Injectable } from '@nestjs/common';
import { ExceptionRegistry } from '@webxsid/nest-exception';

@Injectable()
export class AppService {
    constructor(private readonly exceptionRegistry: ExceptionRegistry) {}

    registerErrors() {
        this.exceptionRegistry.registerError({ code: 'E003', message: 'Invalid request' });
    }
}

Extending the Exception Handler

  • Use the ExceptionHandlerService to customize error handling for specific exceptions:
import { Injectable, OnModuleInit } from '@nestjs/common';
import { ExceptionHandlerService } from '@webxsid/nest-exception';
import { ArgumentsHost, HttpStatus } from '@nestjs/common';

@Injectable()
export class MongoErrorHandler implements OnModuleInit {
    constructor(private readonly exceptionHandlerService: ExceptionHandlerService) {}

    onModuleInit() {
        this.exceptionHandlerService.register(MongoError, (exception: MongoError, host: ArgumentsHost) => {
            const response = host.switchToHttp().getResponse();
            response.status(HttpStatus.BAD_REQUEST).json({
                statusCode: HttpStatus.BAD_REQUEST,
                errorCode: 'MONGO_ERROR',
                message: exception.message,
                timestamp: new Date().toISOString(),
            });
        });
    }
}
  • Add the handler class to the module providers:
@Module({
    imports: [AppExceptionModule.forRoot(/*...*/)],
    providers: [MongoErrorHandler]
})
export class AppModule {}

Throwing Custom Exceptions

  • Use the AppException class to throw predefined errors:
import { Injectable } from '@nestjs/common';
import { AppException } from '@webxsid/nest-exception';

@Injectable()
export class AppService {
    async getUser(id: string) {
        const user = await this.userService.findById(id);
        if (!user) {
            throw new AppException('E001');
        }
        return user;
    }
}

How It Works

The 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:

1. ✅ Passing a Registered Error Code

If the error code exists in the registry (either pre-registered in the module or added dynamically), AppException will: • Retrieve the corresponding error message and status code. • Construct a structured HTTP response with the correct status, message, and code.

throw new AppException('E001'); 

Output:

{
    "statusCode": 400,
    "errorCode": "E001",
    "message": "User not found",
    "timestamp": "2021-09-01T12:00:00.000Z"
}

(Assuming the error code 'E001' is registered with the message 'User not found' and status code 400)

2. ❌ Passing an Unregistered Error Code or String

If the error code is not found in the registry, AppException will: • Throw an internal server error with the default message and status code. • Log the error using the provided logger service.

throw new AppException('Something went wrong'); 

Output:

{
    "statusCode": 500,
    "errorCode": "UNKNOWN_ERROR",
    "message": "Internal server error",
    "timestamp": "2021-09-01T12:00:00.000Z"
}

🛠️ Development Mode (Stack Trace)

If development mode (isDev: true) is enabled, AppException will also include a stack trace for easier debugging:

{
    "statusCode": 500,
    "errorCode": "UNKNOWN_ERROR",
    "message": "Internal server error",
    "timestamp": "2021-09-01T12:00:00.000Z",
    "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)"
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgements

Author

Siddharth Mittal