# @alessiofrittoli/exception 中文文档

规范地址：https://npmcn.com/package/%40alessiofrittoli/exception/

版本：4\.3\.0
npm 元数据更新时间：2026-11-03T18:57:15.799Z
中文译文更新时间：2026-11-07T00:18:34.904Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：40.1 kB，17 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=24\.15\.0
- 运行依赖：0 个
- 首次发布：2024-12-15T21:47:02.671Z
- 最新版本发布：2026-11-03T18:57:15.532Z
- 近 30 天下载量：2117（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：24（近 12 个月 9 个）

## 中文简介

容易处理出错

## 安装

```sh
npm install @alessiofrittoli/exception
```

也可以使用：`pnpm add @alessiofrittoli/exception`、`yarn add @alessiofrittoli/exception`、`bun add @alessiofrittoli/exception`

## README

# 例外条款

## 容易处理出错

本文件介绍的是: `Exception` class,它提供了处理TypeScript中错误的结构化方法. 它包括自定义属性,例如: `code`, (中文(简体) ), `name`,以及 `status` 用于更详细的错误报告和调试.

 [![Latest version](https://img.shields.io/npm/v/@alessiofrittoli/exception)](https://npmjs.org/package/@alessiofrittoli/exception)[![Test coverage](https://coveralls.io/repos/github/alessiofrittoli/exception/badge.svg) ](https://coveralls.io/github/alessiofrittoli/exception)[![Socket Security score](https://socket.dev/api/badge/npm/package/@alessiofrittoli/exception) ](https://socket.dev/npm/package/@alessiofrittoli/exception/overview)[![npm downloads](https://img.shields.io/npm/dm/@alessiofrittoli/exception.svg) ](https://npmjs.org/package/@alessiofrittoli/exception)[![Dependencies](https://badgen.net/bundlephobia/dependency-count/@alessiofrittoli/exception) ](https://bundlephobia.com/package/@alessiofrittoli/exception)[![Dependencies status](https://img.shields.io/librariesio/release/npm/@alessiofrittoli/exception)](https://libraries.io/npm/%40alessiofrittoli%2Fexception)

 [![minified](https://badgen.net/bundlephobia/min/@alessiofrittoli/exception)](https://bundlephobia.com/package/@alessiofrittoli/exception)[![minizipped](https://badgen.net/bundlephobia/minzip/@alessiofrittoli/exception) ](https://bundlephobia.com/package/@alessiofrittoli/exception)[![Tree shakable](https://badgen.net/bundlephobia/tree-shaking/@alessiofrittoli/exception)](https://bundlephobia.com/package/@alessiofrittoli/exception)

[![Fund this package](https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2)](https://github.com/sponsors/alessiofrittoli)

### 目录

-   [开始](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-getting-started)
-   [发展](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-development)
    -   [地方发展](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-local-development)
    -   [生产建设](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-production-build)
    -   [单位测试](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-unit-tests)
        -   [进行覆盖测试](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-run-tests-with-coverage)
    -   [捐款](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-contributing)
    -   [警卫](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-security)
-   [API 参考](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-api-reference)
    -   [例外选项接口](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-exceptionoptions-interface)
    -   [例外类](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-exception-class)
    -   [中止错误类别](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-aborterror-class)
        -   [中止错误使用情景](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-aborterror-usage-scenarios)
-   [贷项](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-made-with-)

* * *

### 概览

这个 `Exception` 类扩展本地 JavaScript `Error` 对象,添加自定义字段来改进错误分类和处理。 它还包括一种静态工具方法,用以检查一个物体是否是实例 `Exception` 课.

### 开始

运行以下命令开始使用 `@alessiofrittoli/exception` 在您的项目中:

```bash
npm i @alessiofrittoli/exception
```

或使用 `pnpm`

```bash
pnpm i @alessiofrittoli/exception
```

* * *

### 发展

运行以下开始开发

```shell
nvm use

pnpm i
```

#### 地方发展

运行以下

```shell
pnpm dev
```

这将生成未忽略的输出代码, 源图并启用源文件监视器 .

* * *

#### 生产建设

运行以下来创建本地生产建筑

```shell
pnpm build
```

这将生成没有源代码的已修改输出代码 .

* * *

#### 单位测试

通过运行下列程序运行所有定义的测试套件 :

```shell
# Run tests and watch file changes.
pnpm test:watch

# Run tests in a CI environment.
pnpm test:ci
```

* * *

##### 进行覆盖测试

然后开始使用 HTTP 服务器服务覆盖文件 `./coverage` 文件夹.

您可以在您第一次运行此命令时看到空白页 。 只需刷新浏览器即可看到更新 .

```shell
pnpm test:coverage:serve
```

* * *

#### 捐款

献礼真受欢迎!

请参看 [贡献文件](https://npmcn.com/package/%40alessiofrittoli/exception/CONTRIBUTING.md) 了解如何开始为该项目作出贡献的更多信息.

帮助更新此项目 [GitHub 赞助商](https://github.com/sponsors/alessiofrittoli)。 。 。 .

[![GitHub Sponsor](https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2)](https://github.com/sponsors/alessiofrittoli)

* * *

#### 警卫

如果你认为你发现了安全漏洞 我们鼓励你 **_负责地披露此事,不公开问题_**我们将调查所有合法的报告。 电子邮件 `security@alessiofrittoli.it` 披露任何安全弱点.

* * *

### API 参考

#### `ExceptionOptions` 接口

这个 `ExceptionOptions` 界面定义 `Exception` 阶级建筑师.

##### 属性

| 财产 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `name` | `string` | `ExceptionName.Exception` | (备选) 错误界面名称 . |
| `message` | `string` | "未知错误" | (备选) 包含有关错误的技术信息的错误信息 . |
| `title` | `string` | \- 说吧 | (备选) 错误标题 . |
| `description` | `string` | \- 说吧 | (备选) 错误描述 . |
| `code` | `T` | \- 说吧 | (须) 与例外相关的错误代码 . |
| `isCritical` | `boolean` | `false` | (可选)表示错误是否为关键错误. |
| `status` | `number` | \- 说吧 | (可选)与例外相关的HTTP状态代码. |
| `cause` | `unknown` | \- 说吧 | (备选) 错误的原因. |

* * *

#### `Exception` 类

这个 `Exception` 类扩展 `Error` 对象和执行 `ExceptionOptions` 接口.

##### 构造器

构造器初始化一个 `Exception` 选项.

###### 参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `options` | `ExceptionOptions` | (须) 包含错误选项的对象. |

###### 示例

```ts
import { Exception } from '@alessiofrittoli/exception'

try {
  throw new Exception({
    message: 'Resource not found'
    code: 'ERR:NOTFOUND',
    status: 404,
  })
} catch (error) {
  console.error(error)
}
```

##### 静态方法

###### `isException`

用于检查对象是否为实例的工具方法 `Exception` 课.

委员会也支持JSON代表联合国 `Exception` 类(通常通过服务器回复返回).

###### 示例

```ts
try {
  throw new Exception({ message: 'Something went wrong', code: 'ERR:UNKNOWN' })
} catch (error) {
  if (Exception.isException(error)) {
    // we can safely access `Exception` properties
    console.error(`Error [${error.code}]: ${error.message}`)
  } else {
    console.error(error)
  }
}
```

```ts
import { ExceptionName } from '@alessiofrittoli/exception'

/** Simulates JSON Exception returned by a server JSON Response. */
const error = JSON.parse(
  JSON.stringify(
    new Exception({
      name: ExceptionName.AbortError,
      message: 'Exception with custom name.',
      code: 0,
    }),
  ),
)

console.log(Exception.isException(error)) // Outputs: true
console.log(new Exception(error)) // Outputs: [Exception]
```

* * *

#### `AbortError` 类

这个 `AbortError` 类扩展 [`Exception` 类](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-exception-class) 并提供一个预设配置,以便于使用.

##### 构造器

构造器初始化一个 `AbortError` 选项.

###### 参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `options` | `AbortErrorOptions` | 包含错误选项的对象. |
|  |  | 它延伸 [`ExceptionOptions` 接口](https://npmcn.com/package/%40alessiofrittoli/exception/#readme-exceptionoptions-interface) 并省略 `name` 属性. |
|  |  | 这个 `code` 默认为 `ErrorCode.ABORT` 但可以选择定制. |

* * *

##### 中止错误使用情景

###### 精确中止处理出错

```ts
import { AbortError } from '@alessiofrittoli/exception/abort'

try {
  const controller = new AbortController()
  const { signal } = controller

  button.addEventListener('click', () => {
    controller.abort(new AbortError({ message: 'User cancelled the request.' }))
  })

  await fetch(..., { signal })
} catch (error) {
  if (AbortError.isException(error)) {
    if (AbortError.isAbortError(error)) {
      // handle abort error
      console.log(error.code) // `error.code` is type of `ErrorCode.ABORT`.
      return
    }

    // handle other Exception errors
    return
  }

  // handle other unknown errors
}
```

* * *

###### 使用自定义中止出错代码

```ts
import { AbortError } from '@alessiofrittoli/exception/abort'

enum ApplicationErrorCode {
  CUSTOM_CODE = 'ERR:CUSTOM_ABORT_CODE',
}

try {
  const controller = new AbortController()
  const { signal } = controller

  button.addEventListener('click', () => {
    controller.abort(
      new AbortError({
        message: 'User cancelled the request.',
        code: ApplicationErrorCode.CUSTOM_CODE,
      }),
    )
  })

  await fetch('', { signal })
} catch (error) {
  if (AbortError.isException<ApplicationErrorCode>(error)) {
    if (AbortError.isAbortError(error, ApplicationErrorCode.CUSTOM_CODE)) {
      // handle abort error
      console.log(error.code) // `error.code` is type of `CustomAbortCode.CUSTOM_CODE`.
      return
    }

    // handle other Exception errors
    return
  }

  // handle other unknown errors
}
```

* * *

### 由 所制

<table><tbody><tr><td><img alt="avatar" src="https://avatars.githubusercontent.com/u/35973186" loading="lazy" decoding="async" referrerpolicy="no-referrer"></td><td><table><tbody><tr><td><a href="https://github.com/alessiofrittoli" rel="nofollow noopener noreferrer">阿莱西奥·弗里托利</a></td></tr><tr><td><small><a href="https://alessiofrittoli.it/" rel="nofollow noopener noreferrer">https://alessiofrittoli.it (英语)</a> | <a href="mailto:info@alessiofrittoli.it" rel="nofollow noopener noreferrer">(原始内容存档于2018-10-21) (英语). info.it</a></small></td></tr></tbody></table></td></tr></tbody></table>

## 常见问题

### @alessiofrittoli/exception 是什么？

容易处理出错

### 如何安装 @alessiofrittoli/exception？

在项目目录运行 npm install @alessiofrittoli/exception，或使用 pnpm add / yarn add / bun add。

### @alessiofrittoli/exception 支持 TypeScript 吗？

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

### @alessiofrittoli/exception 支持 ESM 还是 CommonJS？

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

### @alessiofrittoli/exception 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=24\.15\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @alessiofrittoli/exception 可以商用吗？

@alessiofrittoli/exception 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @alessiofrittoli/exception 的下载量有多少？

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

### @alessiofrittoli/exception 还在维护吗？

最新版本 4\.3\.0 发布于 2026/11/04（4 天前）；至今共发布 24 个版本，其中过去 12 个月发布了 9 个；首次发布于 2024/12/16。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

