New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@betsys-nestjs/exception-handling

Package Overview
Dependencies
Maintainers
9
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@betsys-nestjs/exception-handling

This library is responsible for handling exception thrown in application

  • 4.0.0
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
1
decreased by-80%
Maintainers
9
Weekly downloads
 
Created
Source

Exception Handling Library

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

Dependencies

PackageVersion
@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 {
}

The signature of exceptions is always the same and looks like this:
{
  "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');
    }
}

FAQs

Package last updated on 13 Nov 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc