본문으로 건너뛰기
i18n-error-base
한국어
Esc
↑↓이동↵열기⌘J미리보기
이 페이지에서

사용법

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

기본 흐름

오류 클래스를 정의합니다

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

이 페이지가 도움이 되었나요?