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

@tresdoce-nestjs-toolkit/filters

v2.0.12

Published

Tresdoce NestJS Toolkit - Librería para filtrar y formatear las excepciones

Readme

⚠️ Es importante tener en cuenta que este filtro se encuentra implementado en el package @tresdoce-nestjs-toolkit/paas, ya que es una funcionalidad core para el starter.

Este módulo está pensado para ser utilizado en NestJS Starter, o cualquier proyecto que utilice una configuración centralizada, siguiendo la misma arquitectura del starter.

Glosario


📝 Requerimientos básicos

🛠️ Instalar dependencia

npm install -S @tresdoce-nestjs-toolkit/filters
yarn add @tresdoce-nestjs-toolkit/filters

📦 Dependencias internas

Este paquete requiere los siguientes paquetes del toolkit:

| Paquete | Razón | | ------------------------------------------ | ---------------------------------------------------------------- | | @tresdoce-nestjs-toolkit/core | Tipos Typings.AppConfig, decoradores base y utilidades comunes |

⚙️ Configuración

Registrar ExceptionsFilter como filtro global en main.ts, pasándole la configuración centralizada de la aplicación.

//./src/main.ts
import { ConfigService } from '@nestjs/config';
import { ExceptionsFilter } from '@tresdoce-nestjs-toolkit/filters';

//...

async function bootstrap() {
  //...
  const appConfig = app.get<ConfigService>(ConfigService)['internalConfig']['config'];
  app.useGlobalFilters(new ExceptionsFilter(appConfig));
  //...
}

El filtro lee appConfig.project.apiPrefix para construir el código de error (<API-PREFIX>-<HTTP_STATUS>). Si la configuración no está disponible, usa el valor de fallback 'API-PREFIX'.

👨‍💻 Uso

Para conocer sobre todas las excepciones disponibles, ingresa a la documentación de NestJS - Exception Filters.

El filtro captura cualquier excepción (tanto HttpException como errores genéricos) y responde con un payload normalizado, usando el Content-Type application/problem+json (RFC 7807).

HttpException

try {
  //...
} catch (error) {
  throw new HttpException(error.message, error.response.status);
}
try {
  //...
} catch (error) {
  throw new HttpException(
    {
      message: error.message,
    },
    error.response.status,
  );
}

Custom message HttpException

try {
  //...
} catch (error) {
  throw new HttpException('This is a message', error.response.status);
}
try {
  //...
} catch (error) {
  throw new HttpException(
    {
      message: 'This is a message',
    },
    error.response.status,
  );
}

Simple exception

try {
  //...
} catch {
  throw new Error('this is an error');
}

Respuestas de ejemplo

Error simple (con fallback de prefijo)

{
  "error": {
    "status": 404,
    "instance": "GET /api/characters",
    "code": "API-PREFIX-NOT_FOUND",
    "message": "Request failed with status code 404"
  }
}

Error con prefijo de proyecto configurado

{
  "error": {
    "status": 404,
    "instance": "GET /api/users/123456",
    "code": "MY-API-NOT_FOUND",
    "message": "User #123456 not found"
  }
}

Error de validación con detalle

Cuando la excepción contiene un array de mensajes (por ejemplo, errores de validación de class-validator), el campo message contiene el nombre del error HTTP y el campo detail contiene el listado de mensajes individuales.

{
  "error": {
    "status": 400,
    "instance": "POST /api/users",
    "code": "MY-API-BAD_REQUEST",
    "message": "Bad Request",
    "detail": [
      {
        "message": "firstName must be a string"
      },
      {
        "message": "lastName must be a string"
      },
      {
        "message": "email must be an email"
      },
      {
        "message": "email must be a string"
      }
    ]
  }
}

Error genérico (no HttpException)

Para errores que no son instancias de HttpException, el filtro responde con 500 Internal Server Error y usa el mensaje del error como message.

{
  "error": {
    "status": 500,
    "instance": "GET /api/users",
    "code": "MY-API-INTERNAL_SERVER_ERROR",
    "message": "this is an error"
  }
}

📋 API Reference

ExceptionsFilter

Filtro global que captura todas las excepciones y las normaliza en un payload RFC 7807.

new ExceptionsFilter(appConfig: Typings.AppConfig)
  • Responde con Content-Type: application/problem+json.
  • Usa appConfig.project.apiPrefix para construir el código de error. Si no está configurado, usa 'API-PREFIX' como fallback.
  • Las rutas excluidas (definidas por excludePaths() de @tresdoce-nestjs-toolkit/core) reciben respuestas sin formateo especial.

buildErrorPayload()

Construye el payload de error normalizado a partir de los parámetros de la excepción. Útil para reutilizar la lógica de construcción de errores fuera del filtro (por ejemplo, en servicios de logging).

buildErrorPayload(
  apiPrefix: string,
  method: string,
  url: string,
  exception: any,
): { error: { status: number; instance: string; code: string; message: any; detail: any } }

| Parámetro | Type | Description | | ----------- | -------- | ----------------------------------------------------------- | | apiPrefix | string | Prefijo de la API, usado para construir el código de error. | | method | string | Método HTTP de la request (ej: 'GET', 'POST'). | | url | string | URL de la request (ej: '/api/users/123'). | | exception | any | Excepción capturada (puede ser HttpException o Error). |

getErrorMessage()

Extrae y normaliza el mensaje de error a partir del response de una excepción.

getErrorMessage(
  exceptionResponse: ExceptionResponse | string,
  httpStatus: string,
): ExceptionResponse

Cuando exceptionResponse.message es un array (validaciones), retorna el nombre del error en message y el array mapeado como { message } en detail.

getCode()

Extrae y formatea el código de error en UPPER_SNAKE_CASE a partir del response de la excepción.

getCode(exResponse: ExceptionResponse | string): string

Constantes

| Constante | Valor | Descripción | | ---------------------- | ---------------------------- | --------------------------------------------------------------- | | PROBLEM_CONTENT_TYPE | 'application/problem+json' | Content-Type usado en todas las respuestas de error (RFC 7807). |

Tipos

ExceptionResponse

interface ExceptionResponse {
  error?: string;
  detail?: string;
  message?: string | string[] | ValidationError[];
}

IProblemDetail

Estructura del payload de error retornado en las respuestas.

interface IProblemDetail {
  status: number;
  instance?: string;
  code?: string;
  message: string;
  detail?: string | object | ValidationError[] | Array<string | object>;
  [key: string]: unknown;
}

IErrorDetail

interface IErrorDetail {
  message: string;
  error?: {
    type?: string;
    instance?: string;
    detail?: string;
    code?: string;
  };
}

📄 Changelog

Todos los cambios notables de este paquete se documentarán en el archivo Changelog.