@abinnovision/nestjs-exceptions

中文文档
0.2.1发布于 2026/11/09Apache-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1750

Standardized NestJS exception handling with entity-focused exceptions, HTTP awareness, and built-in support for GraphQL and REST APIs.

原始使用文档
文档目录17 节
  1. Installation
  2. Features
  3. Package entry points
  4. Quick Start
  5. Setup
  6. 1. Configure the global entity name renderer at app startup
  7. 2. Register the exception filter
  8. Drizzle Type Augmentation
  9. 1. Derive an EntityName union from your Drizzle schema
  10. 2. Register the union with EntityRegistry
  11. 3. Use the exceptions directly — entity is now type-checked
  12. API Reference
  13. Core Classes
  14. Entity-Focused Exceptions
  15. Entity Name Renderer
  16. Creating Custom Exceptions
  17. License

@abinnovision/nestjs-exceptions

npm

NestJS exception handling with entity-focused exceptions and GraphQL support.

Installation

yarn add @abinnovision/nestjs-exceptions

Features

  • AppException: Transport-agnostic base exception class with typed metadata support
  • HttpAwareException: Opt-in interface for HTTP status codes and headers
  • MultiAppException: Wrapper for multiple exceptions
  • GenericExceptionFilter: Unified error handling for HTTP and GraphQL
  • Entity-focused exceptions: EntityNotFoundException, EntityMutationFailedException with configurable entity display names

Package entry points

The package exposes two entry points:

  • @abinnovision/nestjs-exceptions — base classes, the HTTP-aware interface, MultiAppException, and GenericExceptionFilter.
  • @abinnovision/nestjs-exceptions/entity — entity-focused exceptions, the EntityRegistry augmentation point, and the entity name renderer helpers.

Quick Start

import { GenericExceptionFilter } from "@abinnovision/nestjs-exceptions";
import {
  EntityNotFoundException,
  EntityMutationFailedException,
  configureEntityNameRenderer,
} from "@abinnovision/nestjs-exceptions/entity";

/**
 * Configure entity display names at app startup.
 */
configureEntityNameRenderer({
  user: "User",
  organization: "Organization",
  user_profile: "User profile",
});

throw new EntityNotFoundException({ entity: "user", entityId: "123" });
// Error message: "User with ID '123' not found"

throw new EntityMutationFailedException({
  entity: "user",
  entityId: "123",
  mutationType: "update",
});
// Error message: "Failed to update User with ID '123'"

Setup

1. Configure the global entity name renderer at app startup

// main.ts (or app.module.ts constructor)
import { configureEntityNameRenderer } from "@abinnovision/nestjs-exceptions/entity";

configureEntityNameRenderer({
  user: "User",
  organization: "Organization",
  user_profile: "User profile",
});

2. Register the exception filter

// main.ts
import { GenericExceptionFilter } from "@abinnovision/nestjs-exceptions";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new GenericExceptionFilter());
  await app.listen(3000);
}

Drizzle Type Augmentation

For type-safe entity names derived from your Drizzle schema, augment the EntityRegistry interface exposed from @abinnovision/nestjs-exceptions/entity. Once augmented, every entity-focused exception's entity field is automatically narrowed — no subclassing required.

1. Derive an EntityName union from your Drizzle schema

// src/common/exceptions/entity-types.ts
import type { Table } from "drizzle-orm";
import type { db } from "../../database";

type GetTableName<T> = T extends Table<infer C> ? C["name"] : never;
type TableKeys<T> = {
  [K in keyof T]: T[K] extends Table ? K : never;
}[keyof T];

/**
 * Union of all entity names derived from Drizzle schema.
 */
export type EntityName = GetTableName<(typeof db)[TableKeys<typeof db>]>;

2. Register the union with EntityRegistry

// src/common/exceptions/entity-registry.ts
import type { EntityName } from "./entity-types";

declare module "@abinnovision/nestjs-exceptions/entity" {
  interface EntityRegistry {
    entities: EntityName;
  }
}

3. Use the exceptions directly — entity is now type-checked

import { EntityNotFoundException } from "@abinnovision/nestjs-exceptions/entity";

throw new EntityNotFoundException({ entity: "user", entityId: id }); // OK
throw new EntityNotFoundException({ entity: "invalid", entityId: id }); // Type error!

API Reference

Core Classes

AppException<M>

Abstract, transport-agnostic base class for all application exceptions.

abstract class AppException<M = unknown> extends Error {
  abstract code: string;
  readonly details: string;
  readonly meta?: M;
  readonly cause?: Error;
  readonly sourcePointer?: string;
}

HttpAwareException

Interface implemented by exceptions that carry HTTP-specific information. Implement this on AppException subclasses that should influence HTTP response status codes and headers.

interface HttpAwareException {
  readonly httpStatus: number;
  readonly headers?: Record<string, string>;
}

function isHttpAwareException(value: unknown): value is HttpAwareException;

MultiAppException

Wrapper for multiple exceptions.

import { MultiAppException } from "@abinnovision/nestjs-exceptions";
import { EntityNotFoundException } from "@abinnovision/nestjs-exceptions/entity";

const errors = new MultiAppException([
  new EntityNotFoundException({ entity: "user", entityId: "1" }),
  new EntityNotFoundException({ entity: "user", entityId: "2" }),
]);

GenericExceptionFilter

Exception filter that handles both HTTP and GraphQL contexts.

Entity-Focused Exceptions

All symbols below are imported from @abinnovision/nestjs-exceptions/entity.

EntityNotFoundException

Thrown when an entity is not found.

throw new EntityNotFoundException({ entity: "user", entityId: "123" });
// Code: COMMON__NOT_FOUND
// HTTP Status: 404

EntityMutationFailedException

Thrown when a create/update/delete operation fails.

throw new EntityMutationFailedException({
  entity: "user",
  entityId: "123",
  mutationType: "update", // 'create' | 'update' | 'delete'
});
// Code: COMMON__MUTATION_FAILED
// HTTP Status: 400

Entity Name Renderer

configureEntityNameRenderer(displayNames)

Configure the global entity name renderer. Call once at app startup. Accepts a Record<EntityName, string> mapping entity names to display names.

getEntityDisplayName(entity)

Get the display name for an entity using the global renderer. Falls back to the raw entity name when no mapping is configured.

resetEntityNameRenderer()

Reset to the default (empty) renderer. Useful for testing.

Creating Custom Exceptions

Extend AppException for custom exceptions. Opt into HTTP semantics by implementing HttpAwareException:

import {
  AppException,
  type HttpAwareException,
} from "@abinnovision/nestjs-exceptions";

interface ValidationMeta {
  field: string;
  constraint: string;
}

export class ValidationException
  extends AppException<ValidationMeta>
  implements HttpAwareException
{
  public override code = "VALIDATION__FAILED";
  public readonly httpStatus = 400;

  public constructor(field: string, constraint: string) {
    super(`Validation failed for field '${field}': ${constraint}`, {
      meta: { field, constraint },
    });
  }
}

Or extend EntityFocusedAppException for entity-related exceptions:

import { type HttpAwareException } from "@abinnovision/nestjs-exceptions";
import {
  EntityFocusedAppException,
  type EntityFocusedArgs,
} from "@abinnovision/nestjs-exceptions/entity";

import type { AppExceptionOptsWithoutMeta } from "@abinnovision/nestjs-exceptions";

export class DuplicateEntityException
  extends EntityFocusedAppException
  implements HttpAwareException
{
  public override code = "COMMON__DUPLICATE";
  public readonly httpStatus = 409;

  public constructor(
    args: EntityFocusedArgs,
    opts?: AppExceptionOptsWithoutMeta,
  ) {
    super(
      args,
      (displayName, entityId) =>
        `${displayName} with ID '${entityId}' already exists`,
      opts,
    );
  }
}

License

Apache-2.0

版本与发布记录

@abinnovision/nestjs-exceptions 共发布 10 个版本,首次发布于 2026/05/13;过去 12 个月发布了 10 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.1latest2026/11/09今天
0.2.1-beta.28beta2026/11/081 天前
0.2.02026/10/1228 天前
0.2.0-beta.52026/10/1228 天前
0.2.0-beta.42026/10/081 个月前
0.2.0-beta.22026/05/195 个月前

关于 @abinnovision/nestjs-exceptions 的常见问题

@abinnovision/nestjs-exceptions 是什么?

Standardized NestJS exception handling with entity-focused exceptions, HTTP awareness, and built-in support for GraphQL and REST APIs.

如何安装 @abinnovision/nestjs-exceptions?

在项目目录运行 npm install @abinnovision/nestjs-exceptions,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@nestjs/core(^11.0.0 || ^12.0.0)、@nestjs/common(^11.0.0 || ^12.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@abinnovision/nestjs-exceptions 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@abinnovision/nestjs-exceptions 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@abinnovision/nestjs-exceptions 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^20.19.0 || >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@abinnovision/nestjs-exceptions 可以商用吗?

@abinnovision/nestjs-exceptions 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@abinnovision/nestjs-exceptions 的下载量有多少?

根据 npm 官方下载统计,@abinnovision/nestjs-exceptions 在 2026/10/05 – 2026/11/03 这 30 天内被下载 1,750 次,日均约 58 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@abinnovision/nestjs-exceptions 还在维护吗?

最新版本 0.2.1 发布于 2026/11/09(今天);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/05/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。