---
title: 使用方法
description: 定义错误类、注册消息、切换语言、前缀、回退的基本操作。
---

## 基本流程 [#basic-flow]

1. **定义错误类**

    继承 `I18nErrorBase<TMeta>`，并将用于消息生成的信息定义为 `TMeta`。

2. **注册各语言的消息**

    使用 `setErrorMessage` 注册类与语言对应的消息。

3. **切换语言并读取 message**

    通过 `setGlobalConfig({ lang })` 切换，并读取 `error.message`。

```ts
import { setGlobalConfig } from "valibot";
import { I18nErrorBase, setErrorMessage } from "i18n-error-base";

class BusinessRuleError extends I18nErrorBase<{ code: string; limit: number }> {
  public constructor(meta: { code: string; limit: number }) {
    super(meta, ({ code, limit }) => `Code: ${code}, Limit: ${limit}`);
  }
}

setErrorMessage(
  BusinessRuleError,
  ({ code, limit }) => `コード: ${code}、制限: ${limit}`,
  "ja",
);

const error = new BusinessRuleError({ code: "ERR", limit: 50 });

setGlobalConfig({ lang: "ja" });
console.log(error.message); // コード: ERR、制限: 50

setGlobalConfig({ lang: "en" });
console.log(error.message); // Code: ERR, Limit: 50
```

## 定义错误类 [#define-error-class]

`TMeta` 是用于消息生成的附带信息。保留在 `error.meta` 中，并传递给注册函数。

```ts
import { I18nErrorBase } from "i18n-error-base";

class NotFoundError extends I18nErrorBase<{ resource: string }> {}

const error = new NotFoundError({ resource: "user" }, "fallback message");
console.log(error.meta); // { resource: "user" }
```

第二个参数是字符串或 `(meta) => string`。第三个参数是与 `Error` 相同的 `{ cause }` 等选项。

```ts
class TestError extends I18nErrorBase<{ code: string }> {}

const cause = new Error("original");
const error = new TestError({ code: "ERR" }, "something went wrong", { cause });
console.log(error.cause === cause); // true
```

将 `TMeta` 设为 `undefined` 时可以省略 `meta`。

```ts
class NoMetaError extends I18nErrorBase<undefined> {}

const a = new NoMetaError("no meta");
const b = new NoMetaError(undefined, "no meta");
console.log(a.meta); // undefined
```

:::note
请勿直接 `new`，务必继承后使用。注册按类区分，父类的注册不会继承给子类。
:::

## 注册消息 [#register-message]

`setErrorMessage` 注册按类、按语言的生成函数。

```ts
import { I18nErrorBase, setErrorMessage } from "i18n-error-base";

class TestError extends I18nErrorBase<{ code: string }> {}

setErrorMessage(TestError, ({ code }) => `エラーコード: ${code}`, "ja");
setErrorMessage(TestError, "something went wrong", "en");
```

也可指定字符串。语言也可用数组指定。

```ts
const message = ({ code }: { code: string }) => `エラーコード: ${code}`;
setErrorMessage(TestError, message, ["ja", "ko", "zh"]);
```

同一类与同一语言的重新注册会覆盖。仅在注册时与引用时的构造函数一致时使用，与 `instanceof` 无关。

:::warning[注意在注册前访问]
先读取 `message` 会固定默认值。请在创建实例之前完成注册。
:::

## 切换语言 [#switch-language]

通过 Valibot 的全局配置切换。`message` 在每次读取时参照当前的 `lang`。

```ts
import { setGlobalConfig } from "valibot";

setGlobalConfig({ lang: "ja" });
console.log(error.message); // 日本語の登録メッセージ

setGlobalConfig({ lang: "en" });
console.log(error.message); // 英語の登録メッセージ or 既定メッセージ
```

未设置 `lang` 时为 `"en"`。未注册的语言使用构造函数的默认消息。

```ts
setErrorMessage(BusinessRuleError, () => "日本語メッセージ", "ja");

setGlobalConfig({ lang: "fr" });
console.log(error.message); // "Code: ERR, Limit: 50"（既定メッセージ）
```

## 添加前缀 [#prefix]

`static prefix` 会拼接到解析后消息的开头。对翻译消息和默认消息都生效。

```ts
class PrefixedError extends I18nErrorBase<{ code: string }> {
  static {
    this.prefix = "[ERROR] ";
  }
}

setErrorMessage(PrefixedError, ({ code }) => `code is ${code}`, "ja");
const error = new PrefixedError({ code: "ERR" }, "fallback");

setGlobalConfig({ lang: "ja" });
console.log(error.message); // "[ERROR] code is ERR"

setGlobalConfig({ lang: "en" });
console.log(error.message); // "[ERROR] fallback"
```

未设置时按原样返回。

## 作为 Error 的行为 [#error-behavior]

- `error instanceof Error`、`instanceof I18nErrorBase`、`instanceof 具体类` 均为 `true`
- `String(error)` / `error.toString()` 包含解析后的消息（例如 `"Error: ..."`）
- `cause` 通过 `{ cause }` 保留

## 常见模式 [#common-patterns]

### 在构造函数中固定默认消息 [#fix-default-message-in-constructor]

```ts
class BusinessRuleError extends I18nErrorBase<{ code: string; limit: number }> {
  public constructor(meta: { code: string; limit: number }, options?: ErrorOptions) {
    super(meta, ({ code, limit }) => `Code: ${code}, Limit: ${limit}`, options);
  }
}
```

调用方只需传递 `meta`，可避免默认文本的重复。

### 批量注册多种语言 [#register-multiple-languages]

```ts
setErrorMessage(MyError, "エラーが発生しました", ["ja"]);
setErrorMessage(MyError, "An error occurred", ["en", "en-US"]);
```

语言代码不会规范化。`"en"` 与 `"en-US"` 是不同的键，请明确注册所需的代码。
