# @aircall/exception-zod 中文文档

规范地址：https://npmcn.com/package/%40aircall/exception-zod/

版本：0\.3\.0
npm 元数据更新时间：2025-11-25T15:18:27.908Z
中文译文更新时间：2026-11-06T17:26:24.579Z
软件包许可：未声明

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

原始 npm 页面：https://www.npmjs.com/package/%40aircall/exception-zod
原文对照：https://npmcn.com/package/%40aircall/exception-zod/?lang=original

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

- 包体积（解压后）：12.8 kB，6 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：zod ^3\.x，@aircall/exception 0\.x
- 首次发布：2024-04-16T22:21:44.965Z
- 最新版本发布：2025-09-04T07:29:10.120Z
- 近 30 天下载量：2588（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：7（近 12 个月 0 个）

## 中文简介

此软件包提供了处理应用程序中的例外的简单方法。 它基于 [佐德语Name](https://zod.dev/) 库,是一个 TypeScript- First schema 声明和验证库.

## 安装

```sh
npm install @aircall/exception-zod
```

也可以使用：`pnpm add @aircall/exception-zod`、`yarn add @aircall/exception-zod`、`bun add @aircall/exception-zod`

## README

# 导言

此软件包提供了处理应用程序中的例外的简单方法。 它基于 [佐德语Name](https://zod.dev/) 库,是一个 TypeScript- First schema 声明和验证库.

# 安装

```bash
yarn add @aircall/exception-zod
```

# 如何使用

```typescript
import { Exception } from '@aircall/exception';
import { zodMiddleware } from '@aircall/exception-zod';

// Let's say you have a function which creates a user
// First you define a schema to validate the body of the request
const schema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive()
});

// Let's say you have a lambda handler
export const handler = zodMiddleware(async (event: any) => {
  // You can use the `parse` method to validate the body of the request
  const body = schema.parse(event.body);

  // You can then use the `body` object to create a user
  const user = await createUser(body);

  return {
    statusCode: 200,
    body: JSON.stringify(user)
  };
});

// If the body of the request is invalid, the middleware will throw an exception
// You can catch the exception and return a proper response
try {
  const response = await handler(event);
} catch (error) {
  if (error instanceof Exception) {
    // Manage the exception however you want here
  }

  return {
    statusCode: 400,
    body: JSON.stringify({
      message: error.message
    })
  };
}
```

## REST 一体化

你可以用这个 `zodMiddleware` 同时侧 `restMiddleware` 它会自动分析请求的正文,并对照一个计划加以验证。 如果机身无效,中间软件将使用Aircall常规来抛出一个已经格式化的REST错误.

```typescript
import { restMiddleware } from '@aircall/exception-rest';
import { zodMiddleware } from '@aircall/exception-zod';

const schema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive()
});

export const handler = restMiddleware(
  zodMiddleware(async (event: any) => {
    // You can use the `parse` method to validate the body of the request
    // If the body is invalid, the zod will throw an exception
    // That will be caught by zodMiddleware to convert them to Aircall errors
    // And then by the restMiddleware to convert them to REST responses
    const body = schema.parse(event.body);

    const user = await createUser(body);

    return {
      statusCode: 200,
      body: JSON.stringify(user)
    };
  })
);

// Example of a request
const event = {
  body: JSON.stringify({
    name: 'J',
    email: 'abc',
    age: 1.2
  })
};

const response = await handler(event);

// response
{
  statusCode: 400,
  body: JSON.stringify({
    name: 'UserInputException',
    message: 'Invalid user input',
    code: '0100',
    issues: [
      {
        code: '0103',
        message: 'Input in "name" is too small, minimum is "1" "string"',
        minimum: 1,
        name: 'TooSmallException',
        path: 'name',
        type: 'string'
      },
      {
        name: 'InvalidStringException',
        message: 'Input in "email" has failed the "email" validation',
        code: '0102',
        path: 'email',
        validation: 'email'
      },
      {
        name: 'InvalidTypeException',
        code: '0101',
        expected: 'integer',
        message: 'Input in "age" expected to be "integer" but received "float"',
        path: 'age',
        received: 'float'
      }
    ]
  })
}
```

## 图QL 整合

你可以用这个 `zodMiddleware` 同时侧 `graphqlMiddleware` 它会自动分析请求的正文,并对照一个计划加以验证。 如果机体无效, 中间软件将使用 Aircall 常规丢出一个已经格式化的 GraphQL 错误 .

```typescript

import { graphqlMiddleware } from '@aircall/exception-graphql';
import { zodMiddleware } from '@aircall/exception-zod';

const schema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive()
});

export const handler = graphqlMiddleware(
  zodMiddleware(async (event: any) => {
    // You can use the `parse` method to validate the body of the request
    // If the body is invalid, the zod will throw an exception
    // That will be caught by zodMiddleware to convert them to Aircall errors
    // And then by the graphqlMiddleware to convert them to GraphQL errors
    const body = schema.parse(event.body);

    const user = await createUser(body);

    return {
      user,
      __typename: 'User'
    };
  })
);

// Example of a request

const event = {
  body: JSON.stringify({
    query: `
      mutation {
        createUser(input: { name: "J", email: "abc", age: 1.2 }) {
          __typename

          ... on User {
            id
            name
            email
            age
          }

          ... on UserInputException {
            message

            issues {
              __typename
              message
              code
              path

              ... on TooSmallException {
                minimum
                type
              }

              ... on InvalidStringException {
                validation
              }

              ... on InvalidTypeException {
                received
                expected
              }
            }
          }
        }
      }
    `
  })
};

const response = await handler(event);

// response
{
  data: {
    __typename: 'UserInputException',
    message: 'Invalid user input',
    extensions: {
      code: '0100',
      issues: [
        {
          __typename: 'TooSmallException',
          code: '0103',
          message: 'Input in "name" is too small, minimum is "1" "string"',
          minimum: 1,
          path: 'name',
          type: 'string'
        },
        {
          __typename: 'InvalidStringException',
          code: '0102',
          message: 'Input in "email" has failed the "email" validation',
          path: 'email',
          validation: 'email'
        },
        {
          __typename: 'InvalidTypeException',
          code: '0101',
          message: 'Input in "age" expected to be "integer" but received "float"',
          path: 'age',
          expected: 'integer',
          received: 'float'
        }
      ]
    }
  }
}
```

## 常见问题

### @aircall/exception-zod 是什么？

此软件包提供了处理应用程序中的例外的简单方法。 它基于 佐德语Name 库,是一个 TypeScript- First schema 声明和验证库\.

### 如何安装 @aircall/exception-zod？

在项目目录运行 npm install @aircall/exception-zod，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：zod（^3\.x）、@aircall/exception（0\.x）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @aircall/exception-zod 支持 TypeScript 吗？

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

### @aircall/exception-zod 支持 ESM 还是 CommonJS？

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

### @aircall/exception-zod 可以商用吗？

@aircall/exception-zod 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @aircall/exception-zod 的下载量有多少？

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

### @aircall/exception-zod 还在维护吗？

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

