---
title: 사용법
description: 오류 클래스의 정의, 메시지 등록, 언어 전환, prefix, 폴백의 기본 동작입니다.
---

## 기본 흐름 [#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"`는 별도의 키이므로, 필요한 코드는 명시적으로 등록하십시오.
