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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@betsys-nestjs/exception-handling

v4.0.0

Published

This library is responsible for handling exception thrown in application

Downloads

5

Readme

Exception Handling Library

Library serves for handling of exceptions based on communication type (HTTP, GRPC)

Dependencies

| Package | Version | | --------------------- | ------- | | @grpc/grpc-js | ^1.8.0 | | @betsys-nestjs/logger | ^5.0.0 | | @nestjs/common | ^10.0.0 | | @nestjs/config | ^3.0.0 | | @nestjs/core | ^10.0.0 | | @nestjs/microservices | ^10.0.0 | | express | ^4.0.0 | | reflect-metadata | ^0.1.12 | | rxjs | ^7.1.0 | | class-validator | ^0.13.2 | | class-transformer | ^0.5.1 |

Usage

To start using this library simply import ExceptionHandlingModule and use it like this:

ExceptionHandlingModule has method with this signature forRoot('express' | 'grpc')

import {ExceptionHandlingModule} from '@betsys-nestjs/exception-handling'
import {Module} from "@nestjs/common";

@Module({
    imports: [
        ExceptionHandlingModule.forRoot('http')
    ]
})
class AppModule {
}
{
  "errors": [
    {
      "code": "code",
      "message": "message"
    }
  ]
}

There are 3 different exception types that we distinguish between:

  1. DomainException - An exception that extends BaseDomainException from this library.
  2. RequestValidationException - An exception which is mapped from the exceptions thrown by class-validator library.
  3. All other exceptions - Any other thrown exceptions

Each exception also provides automatic logging, but it's required to initialize the LoggingModule like this:

import {LoggerModule} from "@betsys-nestjs/logger";

LoggerModule.forRoot('http', [])

This bootstraps Logger library globally and is used by ExceptionHandling library automatically.

1. DomainException

Domain exception is thrown within an application and must extend BaseDomainException.

Commonly domain exception is mapped to HttpException within an application controller, we do it automatically via the decorator UseDomainExceptionMapper which specifies the mappings from domain exceptions to http exceptions. You can define any amount of exception mappings. This decorator can be used on either the level of a controller or a specific endpoint within the controller.

Usage example:

import {
    UseDomainExceptionMapper,
    HttpExceptionInterface,
    BaseDomainException
} from '@betsys-nestjs/exception-handling';
import {Controller, Get} from "@nestjs/common";

class TestDomainException extends BaseDomainException {
    static create(): TestDomainException {
        return new TestDomainException(`Domain exception thrown.`);
    }
}

@Controller()
class TestController {
    @UseDomainExceptionMapper<HttpExceptionInterface>(
        'http',
        new Map<string, HttpExceptionInterface>([
            [
                TestDomainException.name,
                {
                    message: 'Test domain exception message',
                    code: 'TEST_DOMAIN_EXCEPTION',
                    statusCode: HttpStatus.CONFLICT,
                },
            ],
        ])
    )
    @Get('domain-exception')
    async testDomainException(): Promise<void> {
        throw TestDomainException.create();
    }
}

2. RequestValidationException

Commonly exceptions thrown by class-validator look like this:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": [
    "email must be an email"
  ]
}

Using this library you will get more readable exception interface defined above.

Usage example:

import {IsString, IsInt} from 'class-validator';
import {Body, Controller, Get} from "@nestjs/common";

class RequestDto {
    @IsString()
    name!: string;

    @IsInt()
    age!: number;
}

@Controller('test')
export class TestController {
    @Get('validation-exception')
    async testValidationException(@Body() dto: RequestDto): Promise<void> {
    }
}

3. LogicException

All other native exceptions thrown within an application will are caught as logic exceptions. They are always mapped to this HttpException with http status of 500:

{
  "errors": [
    {
      "code": "INTERNAL_SERVER_ERROR",
      "message": "Internal server error"
    }
  ]
}

Usage example:

import {Controller, Get} from "@nestjs/common";

@Controller('test')
export class TestController {
    @Get('logic-exception')
    async testLogicException(): Promise<void> {
        throw new Error('Error');
    }
}