---
title: การใช้งาน
description: การดำเนินการพื้นฐานเกี่ยวกับการกำหนดคลาสข้อผิดพลาด การลงทะเบียนข้อความ การสลับภาษา prefix และ fallback
---

## ขั้นตอนพื้นฐาน [#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" }
```

อาร์กิวเมนต์ตัวที่ 2 คือสตริงหรือฟังก์ชัน `(meta) => string` ตัวที่ 3 คือ `{ cause }` และออปชันอื่นของ `Error`

```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` จะต่อไว้หน้าข้อความที่ resolve แล้ว มีผลทั้งข้อความแปลแล้วและข้อความเริ่มต้น

```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()` จะมีข้อความที่ resolve แล้ว (เช่น `"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"]);
```

ไม่มีการ normalize รหัสภาษา `"en"` กับ `"en-US"` เป็นคีย์แยกกัน ลงทะเบียนรหัสที่ต้องการให้ชัดเจน
