Skip to content
i18n-error-base
English
Esc
↑↓navigate↵open⌘Jpreview
On this page

i18n-error-base

A base Error class that switches error messages in sync with Valibot's locale setting.

An Error base class that switches message with Valibot’s lang.

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

class NotFoundError extends I18nErrorBase<{ resource: string }> {}

setErrorMessage(NotFoundError, ({ resource }) => `リソースが見つかりません: ${resource}`, "ja");
setErrorMessage(NotFoundError, ({ resource }) => `Resource not found: ${resource}`, "en");

const error = new NotFoundError({ resource: "user" }, "fallback message");

setGlobalConfig({ lang: "ja" });
console.log(error.message); // リソースが見つかりません: user

setGlobalConfig({ lang: "en" });
console.log(error.message); // Resource not found: user

message refers to lang on each read. Switch without recreating instances. Unregistered languages use the constructor’s default message.

Features

  • Resolves message dynamically with Valibot’s setGlobalConfig({ lang })
  • Register per-language messages later with setErrorMessage. Functions receiving meta are also allowed
  • Unregistered languages use the constructor’s default message
  • Adds a prefix via per-class static prefix
  • Keeps meta and passes it to message factory functions
  • instanceof Error, cause, and stack work as usual

Structure

How it works

message resolves in the following order on each read.

  1. Get lang from getGlobalConfig(). "en" when unset
  2. If a (class × lang) registration exists, run it with meta
  3. Otherwise, return the constructor’s default message
  4. If static prefix is set, prepend it

Next steps

Start with Installation, then see the flow in Usage. Details are in the API Reference.

Was this page helpful?