---
title: Cách dùng
description: Các thao tác cơ bản như định nghĩa error class, đăng ký thông báo, chuyển ngôn ngữ, prefix và fallback.
---

## Quy trình cơ bản [#basic-flow]

1. **Định nghĩa error class**

    Kế thừa `I18nErrorBase<TMeta>` và định nghĩa thông tin tạo thông báo trong `TMeta`.

2. **Đăng ký thông báo theo từng ngôn ngữ**

    Đăng ký thông báo cho từng class và ngôn ngữ bằng `setErrorMessage`.

3. **Chuyển ngôn ngữ và đọc message**

    Chuyển bằng `setGlobalConfig({ lang })` và đọc `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
```

## Định nghĩa error class [#define-error-class]

`TMeta` là thông tin bổ trợ để tạo thông báo. Nó được giữ trong `error.meta` và truyền cho các hàm đã đăng ký.

```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" }
```

Tham số thứ 2 là chuỗi hoặc hàm `(meta) => string`. Thứ 3 là `{ cause }` và các option `Error` khác.

```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
```

Nếu đặt `TMeta` là `undefined`, bạn có thể bỏ qua `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
Đừng dùng `new` trực tiếp; hãy luôn kế thừa. Đăng ký theo từng class, nên đăng ký của cha không truyền cho con.
:::

## Đăng ký thông báo [#register-message]

`setErrorMessage` đăng ký hàm factory cho từng class và ngôn ngữ.

```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");
```

Chuỗi cũng được phép. Ngôn ngữ có thể chỉ định dạng mảng.

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

Đăng ký lại cùng class và ngôn ngữ sẽ ghi đè. Chỉ dùng khi constructor lúc đăng ký và lúc tham chiếu giống nhau, không qua `instanceof`.

:::warning[Lưu ý về truy cập trước khi đăng ký]
Đọc `message` sớm sẽ cố định giá trị mặc định. Hãy đăng ký trước khi tạo instance.
:::

## Chuyển ngôn ngữ [#switch-language]

Chuyển bằng cài đặt toàn cục của Valibot. `message` tham chiếu `lang` hiện tại mỗi lần đọc.

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

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

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

`lang` chưa thiết lập là `"en"`. Ngôn ngữ chưa đăng ký dùng thông báo mặc định của constructor.

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

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

## Thêm tiền tố [#prefix]

`static prefix` được thêm vào đầu thông báo đã giải quyết. Áp dụng cho cả bản dịch và mặc định.

```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"
```

Nếu không thiết lập, trả về nguyên văn.

## Hành vi dưới dạng Error [#error-behavior]

- `error instanceof Error`, `instanceof I18nErrorBase`, `instanceof` class cụ thể đều là `true`
- `String(error)` / `error.toString()` bao gồm thông báo đã giải quyết (ví dụ: `"Error: ..."`)
- `cause` được giữ qua `{ cause }`

## Mẫu thường gặp [#common-patterns]

### Cố định thông báo mặc định trong constructor [#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);
  }
}
```

Phía gọi chỉ truyền `meta`, tránh lặp lại văn bản mặc định.

### Đăng ký nhiều ngôn ngữ cùng lúc [#register-multiple-languages]

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

Không chuẩn hóa mã ngôn ngữ. `"en"` và `"en-US"` là key riêng biệt, hãy đăng ký rõ ràng các mã cần thiết.
