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
messagedynamically with Valibot’ssetGlobalConfig({ lang }) - Register per-language messages later with
setErrorMessage. Functions receivingmetaare also allowed - Unregistered languages use the constructor’s default message
- Adds a prefix via per-class
static prefix - Keeps
metaand passes it to message factory functions instanceof Error,cause, andstackwork as usual
Structure
Installation
How to add the package and its peer dependency.
Usage
From definition to switching, prefix, and fallback.
API Reference
Specs for I18nErrorBase and setErrorMessage.
How it works
message resolves in the following order on each read.
- Get
langfromgetGlobalConfig()."en"when unset - If a
(class × lang)registration exists, run it withmeta - Otherwise, return the constructor’s default message
- If
static prefixis set, prepend it
Next steps
Start with Installation, then see the flow in Usage. Details are in the API Reference.