跳到内容
i18n-error-base
简体中文
Esc
↑↓导航↵打开⌘J预览
本页内容

使用方法

定义错误类、注册消息、切换语言、前缀、回退的基本操作。

基本流程

定义错误类

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

注册各语言的消息

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

切换语言并读取 message

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

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

定义错误类

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

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 } 等选项。

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。

class NoMetaError extends I18nErrorBase<undefined> {}

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

注册消息

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

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

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

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

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

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

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

切换语言

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

import { setGlobalConfig } from "valibot";

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

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

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

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

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

添加前缀

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

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 instanceof Error、instanceof I18nErrorBase、instanceof 具体类 均为 true
  • String(error) / error.toString() 包含解析后的消息(例如 "Error: ...")
  • cause 通过 { cause } 保留

常见模式

在构造函数中固定默认消息

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,可避免默认文本的重复。

批量注册多种语言

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

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

这个页面有帮助吗?