@alessiofrittoli/exception

中文文档
4.3.0发布于 2026/11/04MITTypeScriptESM + CJS零依赖近 30 天下载 2117

Handle errors with ease

原始使用文档
文档目录7 节
  1. Handle errors with ease
  2. Table of Content
  3. Overview
  4. Getting started
  5. Development
  6. API Reference
  7. Made with ☕

Exception 🚦

Handle errors with ease

This documentation describes the Exception class, which provides a structured way to handle errors in TypeScript. It includes custom properties such as code, name, and status for more detailed error reporting and debugging.

Latest version Test coverage Socket Security score npm downloads Dependencies Dependencies status

minified minizipped Tree shakable

Fund this package

Table of Content


Overview

The Exception class extends the native JavaScript Error object, adding customizable fields to improve error classification and handling. It also includes a static utility method to check if an object is an instance of the Exception class.

Getting started

Run the following command to start using @alessiofrittoli/exception in your projects:

npm i @alessiofrittoli/exception

or using pnpm

pnpm i @alessiofrittoli/exception

Development

Run the following to start development

nvm use

pnpm i

Local development

Run the following

pnpm dev

This will generate unminified output code, sourcemaps and will enable source file watcher.


Production build

Run the following to create a local production build

pnpm build

This will generate minified output code without sourcemaps.


Unit tests

Run all the defined test suites by running the following:

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

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

Run tests with coverage

An HTTP server is then started to serve coverage files from ./coverage folder.

⚠️ You may see a blank page the first time you run this command. Simply refresh the browser to see the updates.

pnpm test:coverage:serve

Contributing

Contributions are truly welcome!

Please refer to the Contributing Doc for more information on how to start contributing to this project.

Help keep this project up to date with GitHub Sponsor.

GitHub Sponsor


Security

If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email [email protected] to disclose any security vulnerabilities.


API Reference

ExceptionOptions Interface

The ExceptionOptions interface defines the optional parameters for the Exception class constructor.

Properties
PropertyTypeDefaultDescription
namestringExceptionName.Exception(Optional) The error interface name.
messagestring"Unknown error."(Optional) The error message containing technical informations about the error.
titlestring-(Optional) The error title.
descriptionstring-(Optional) The error description.
codeT-(Required) The error code associated with the Exception.
isCriticalbooleanfalse(Optional) Indicates whether the error is a critical error.
statusnumber-(Optional) The HTTP status code associated with the Exception.
causeunknown-(Optional) The error cause.

Exception Class

The Exception class extends the Error object and implements the ExceptionOptions interface.

Constructor

The constructor initializes an Exception instance with a custom message and options.

Parameters
ParameterTypeDescription
optionsExceptionOptions(Required) An object containing the error options.
Example
import { Exception } from '@alessiofrittoli/exception'

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

A utility method to check if an object is an instance of the Exception class.

It supports also a JSON representation of the Exception class (commonly returned by server responses).

Example
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)
  }
}
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 Class

The AbortError class extends the Exception Class and offers a preset configuration for easier usage.

Constructor

The constructor initializes an AbortError instance with a custom message and options.

Parameters
ParameterTypeDescription
optionsAbortErrorOptionsAn object containing the error options.
It extends the ExceptionOptions Interface and omit the name property.
The code defaults to ErrorCode.ABORT but can be optionally customized.

AbortError Usage Scenarios
Precise Abort Errors Handling
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
}

Using custom Abort Error codes
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
}

Made with ☕

avatar
Alessio Frittoli
https://alessiofrittoli.it | [email protected]

版本与发布记录

@alessiofrittoli/exception 共发布 24 个版本,首次发布于 2024/12/16;过去 12 个月发布了 9 个版本。

版本发布日期距今
4.3.0latest2026/11/044 天前
4.2.02026/10/2414 天前
4.1.12026/10/2316 天前
4.1.02026/10/061 个月前
4.0.02026/10/061 个月前
3.5.02025/12/0511 个月前

关于 @alessiofrittoli/exception 的常见问题

@alessiofrittoli/exception 是什么?

Handle errors with ease

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