# @abinnovision/nestjs-exceptions 中文文档

规范地址：https://npmcn.com/package/%40abinnovision/nestjs-exceptions/

版本：0\.2\.1
npm 元数据更新时间：2026-11-09T15:25:45.356Z
中文译文更新时间：2026-11-09T20:22:48.176Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40abinnovision/nestjs-exceptions
原文对照：https://npmcn.com/package/%40abinnovision/nestjs-exceptions/?lang=original
项目主页：https://github.com/abinnovision/nestjs-commons#readme
源码仓库：https://github.com/abinnovision/nestjs-commons

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：76.7 kB，42 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：^20\.19\.0 \|\| \>=22\.12\.0
- 运行依赖：0 个
- peer 依赖：graphql ^16\.0\.0 \|\| ^17\.0\.0，@nestjs/core ^11\.0\.0 \|\| ^12\.0\.0，@nestjs/common ^11\.0\.0 \|\| ^12\.0\.0，@nestjs/graphql ^12\.0\.0 \|\| ^13\.0\.0 \|\| ^14\.0\.0
- 首次发布：2026-05-13T14:19:38.182Z
- 最新版本发布：2026-11-09T15:25:44.783Z
- 近 30 天下载量：1750（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 10 个）

## 中文简介

标准化的NestJS例外处理,以实体为重点的例外,HTTP意识,以及对GraphQL和REST API的内置支持.

## 安装

```sh
npm install @abinnovision/nestjs-exceptions
```

也可以使用：`pnpm add @abinnovision/nestjs-exceptions`、`yarn add @abinnovision/nestjs-exceptions`、`bun add @abinnovision/nestjs-exceptions`

## README

# @abinnovision/nestjs-例外

[![npm](https://img.shields.io/npm/v/@abinnovision/nestjs-exceptions?style=flat-square)](https://www.npmjs.com/package/@abinnovision/nestjs-exceptions)

NestJS例外处理,以实体为重点的例外和GraphQL支持.

## 安装

```bash
yarn add @abinnovision/nestjs-exceptions
```

## 特征

-   **应用例外**: 有输入元数据的运输-不可知基例外类
-   **Http 软件排除**: HTTP 状态代码和信头的 Opt- in接口
-   **多选项**: 多个例外的折叠器
-   **常规例外过滤器**: HTTP 和 GraphQL 的统一错误处理
-   **以实体为重点的例外情况**数字 : `EntityNotFoundException`, (中文(简体) ), `EntityMutationFailedException` 可配置实体显示名称

## 软件包切入点

该套件暴露出两个切入点:

-   `@abinnovision/nestjs-exceptions` ——基础类,HTTP-意识接口, `MultiAppException`,以及 `GenericExceptionFilter`。 。 。 .
-   `@abinnovision/nestjs-exceptions/entity` - 以实体为重点的例外情况 `EntityRegistry` 增强点,以及实体名称渲染器辅助器.

## 快速启动

```typescript
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'"
```

## 设置

### 1\. 在应用程序启动时配置全球实体名称渲染器

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

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

### 2\. 登记例外过滤器

```typescript
// 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 方案的安全类型实体名称,请添加 `EntityRegistry` 界面从 `@abinnovision/nestjs-exceptions/entity`。 。 。 . 一旦扩大,每个实体的例外 `entity` 字段自动 缩小——不需要子分类.

### 1\. 衍生物a `EntityName` 联合从你的德利兹计划

```typescript
// 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\. 工会登记 `EntityRegistry`

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

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

### 3\. 直接使用例外情况 -- -- `entity` 现在已选中类型

```typescript
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 参考

### 核心类

#### `AppException<M>`

摘要,所有应用例外的运输不可知基等.

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

#### `HttpAwareException`

由带有HTTP特定信息的例外执行接口. 在 `AppException` 应影响 HTTP 的子类 响应状态代码和信头.

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

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

#### `MultiAppException`

用于多个例外的包装.

```typescript
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`

处理 HTTP 和 GraphQL 上下文的例外过滤器 .

### 实体除外

以下所有符号均从 `@abinnovision/nestjs-exceptions/entity`。 。 。 .

#### `EntityNotFoundException`

未找到实体时抛出 .

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

#### `EntityMutationFailedException`

当创建/更新/删除操作失败时丢弃 .

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

### 实体名称渲染器

#### `configureEntityNameRenderer(displayNames)`

配置全局实体名称渲染器 。 启动时打一次电话. 接受一个 `Record<EntityName, string>` 绘图要显示名称的实体名称 .

#### `getEntityDisplayName(entity)`

获取使用全局渲染器的实体的显示名称 。 倒计时 未配置映射时的原始实体名称.

#### `resetEntityNameRenderer()`

重置到默认( 空) 渲染器 。 有用的测试.

## 创建自定义例外

扩展 `AppException` 用于海关例外。 选择到 HTTP 语义 执行 `HttpAwareException`数字 :

```typescript
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 },
    });
  }
}
```

或者延长 `EntityFocusedAppException` 与实体有关的例外情况:

```typescript
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,
    );
  }
}
```

## 许可证

阿帕奇 - 2.0

## 常见问题

### @abinnovision/nestjs-exceptions 是什么？

标准化的NestJS例外处理,以实体为重点的例外,HTTP意识,以及对GraphQL和REST API的内置支持\.

### 如何安装 @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 和提交记录判断。

