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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@wisemen/api-error

v0.0.3

Published

This package provides a structured and standardized way to handle API errors within a NestJS application. It is designed to be extensible, easy to use, and to integrate seamlessly with `@nestjs/swagger` for automated API documentation.

Readme

API error package for NestJS

This package provides a structured and standardized way to handle API errors within a NestJS application. It is designed to be extensible, easy to use, and to integrate seamlessly with @nestjs/swagger for automated API documentation.

Features

  • Standardized Error Classes: A collection of abstract classes for common HTTP errors (BadRequestApiError, NotFoundApiError, ConflictApiError, etc.), each pre-configured with the correct HTTP status code.
  • Custom Error Creation: An ApiError base class that allows you to define your own custom, domain-specific errors.
  • Rich Error Metadata: Decorators to enrich your errors with unique codes (@ApiErrorCode) and additional metadata (@ApiErrorMeta).
  • Swagger Integration: Automatically generate detailed and accurate Swagger documentation for your error responses with decorators like @ApiNotFoundErrorResponse and @ApiBadRequestErrorResponse.
  • Type-Safe: Written in TypeScript to ensure full type-safety for your error objects.

Philosophy

The core philosophy is to treat API errors as first-class citizens of your domain. By creating specific, descriptive error classes, you can make your codebase more explicit and easier to understand. This approach ensures that error handling is not an afterthought but a well-defined part of your application's architecture.

This package promotes:

  • Clarity: Machine-readable error codes and human-readable details.
  • Consistency: A uniform error response structure across all endpoints.
  • Discoverability: Automatic Swagger documentation makes it easy for API consumers to understand potential errors.
  • Extensibility: Easily create new error types that fit your application's specific needs.

Example

Here's how you can define and use a custom API error.

1. Define a custom error

Create a new class that extends one of the provided base error classes. Use decorators to add a unique code and any relevant metadata.

// src/users/errors/user-not-found.api-error.ts

import { NotFoundApiError } from "@wisemen/api-error";
import { ApiErrorCode } from "@wisemen/api-error";
import { ApiErrorMeta } from "@wisemen/api-error";

class UserNotFoundErrorMeta {
  @ApiProperty()
  readonly userId: string;
}

@ApiErrorMeta(UserNotFoundErrorMeta)
export class UserNotFoundError extends NotFoundApiError {
  @ApiErrorCode("user_not_found")
  readonly code: "user_not_found";

  constructor(userId: string) {
    super(`User with id '${userId}' not found.`);
    this.meta = { userId };
  }
}

2. Use the error in your controller

In your controller, use the custom error and document it with the corresponding response decorator.

// src/users/users.controller.ts

import { Controller, Get, Param } from "@nestjs/common";
import { ApiNotFoundErrorResponse } from "@wisemen/api-error";
import { UserNotFoundError } from "./errors/user-not-found.api-error.ts";

@Controller("users")
export class UsersController {
  @Get(":id")
  @ApiNotFoundErrorResponse(UserNotFoundError)
  async findOne(@Param("id") id: string) {
    const user = await this.usersService.findOne(id);

    if (!user) {
      throw new UserNotFoundError(id);
    }

    return user;
  }
}

When a UserNotFoundError is thrown, the client will receive a 404 Not Found response with the following body:

{
  "errors": [
    {
      "status": "404",
      "code": "user_not_found",
      "detail": "User with id 'some-id' not found.",
      "meta": {
        "userId": "some-id"
      }
    }
  ]
}

The Swagger documentation will also be updated to show that this endpoint can return a 404 error with the specified structure.

Deep Dive

The ApiError base class

The abstract ApiError class is the foundation of this package.

export abstract class ApiError extends Error {
  abstract readonly code: string;
  abstract readonly status: string;
  abstract readonly meta: unknown;
  readonly detail?: string;
}
  • status: The HTTP status code for the error.
  • code: A unique, machine-readable string identifying the error.
  • detail: A human-readable explanation specific to this occurrence of the problem.
  • meta: An object containing non-standard meta-information about the error.

Decorators

  • @ApiErrorStatus(status: HttpStatus): Sets the status property for an error class and makes it a read-only property in the Swagger documentation.
  • @ApiErrorCode(code: string): Sets the code property for an error class and makes it a read-only property with a specific enum value in the Swagger documentation.
  • @ApiErrorMeta(meta: T): Defines the shape of the meta object for an error class for Swagger documentation.
  • @ApiErrorResponse(status: HttpStatus, errors: Array<ClassConstructor<ApiError>>): A generic decorator to document one or more errors for a given HTTP status in a controller method.
  • @ApiNotFoundErrorResponse(...), @ApiBadRequestErrorResponse(...), @ApiConflictErrorResponse(...): Convenience decorators that are shortcuts for @ApiErrorResponse with a pre-filled status code.