1.0.2 • Published 10 months ago

@origins-digital/error-utils v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

@origins-digital/error

A comprehensive error handling package for NestJS applications that provides standardized error responses, HTTP exception handling, and Swagger documentation.

Installation

npm install @origins-digital/error

Features

  • Standardized error responses
  • HTTP exception handling
  • Automatic Swagger documentation for errors
  • Axios error handling and transformation
  • Development-friendly error details
  • Custom error filters

Usage

Basic Setup

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { ErrorFilter } from '@origins-digital/error';

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

Using HTTP Exceptions

import { Controller } from '@nestjs/common';
import { ApiErrors } from '@origins-digital/error';

@Controller('users')
@ApiErrors([400, 401, 403, 404, 500]) // Document common errors
export class UsersController {
  @Get(':id')
  @ApiErrors([404]) // Document specific endpoint errors
  async getUser(@Param('id') id: string) {
    // Your code here
  }
}

Handling Axios Errors

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { raiseError } from '@origins-digital/error';

@Injectable()
export class ExternalService {
  constructor(private readonly httpService: HttpService) {}

  async fetchData() {
    try {
      const response = await this.httpService
        .get('https://api.example.com/data')
        .toPromise();
      return response.data;
    } catch (error) {
      // raiseError will format the Axios error properly for logging and error handling
      raiseError(error, { service: 'example-api' });
    }
  }

  async createResource(data: any) {
    try {
      const response = await this.httpService
        .post('https://api.example.com/resources', data)
        .toPromise();
      return response.data;
    } catch (error) {
      // The error will be properly formatted with status code and message
      raiseError(error, { service: 'example-api' });
    }
  }

  async updateResource(id: string, data: any) {
    try {
      const response = await this.httpService
        .patch(`https://api.example.com/resources/${id}`, data)
        .toPromise();
      return response.data;
    } catch (error) {
      // Error will be properly formatted for logging
      raiseError(error, { service: 'example-api' });
    }
  }
}

Error Response Format

All errors follow a standardized format:

{
  "statusCode": 404,
  "type": "NotFoundException",
  "message": "Resource not found",
  "errors": {
    // Optional: Detailed error information
  },
  "stack": "Error stack trace" // Only in development environment
}

Available HTTP Exceptions

The package includes all standard HTTP exceptions:

  • BadRequestException (400)
  • UnauthorizedException (401)
  • PaymentRequiredException (402)
  • ForbiddenException (403)
  • NotFoundException (404)
  • MethodNotAllowedException (405)
  • NotAcceptableException (406)
  • RequestTimeoutException (408)
  • ConflictException (409)
  • GoneException (410)
  • PreconditionFailedException (412)
  • PayloadTooLargeException (413)
  • UnsupportedMediaTypeException (415)
  • UnprocessableEntityException (422)
  • TooManyRequestsException (429)
  • InternalServerErrorException (500)
  • NotImplementedException (501)
  • BadGatewayException (502)
  • ServiceUnavailableException (503)
  • GatewayTimeoutException (504)
  • HttpVersionNotSupportedException (505)

Error Filter Configuration

The error filter can be configured to:

  • Include stack traces in development
  • Customize error response format
  • Handle specific error types
  • Add additional error metadata

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

11 months ago

0.0.8

11 months ago

0.0.7

11 months ago

0.0.6

11 months ago

0.0.5

11 months ago

0.0.4

11 months ago