---
title: i18n-error-base
description: 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`.

```ts
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 [#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 [#structure]

**[Installation](/i18n-error-base/en/installation)**

How to add the package and its peer dependency.

**[Usage](/i18n-error-base/en/usage)**

From definition to switching, prefix, and fallback.

**[API Reference](/i18n-error-base/en/api)**

Specs for `I18nErrorBase` and `setErrorMessage`.

## How it works [#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

:::tip
Registered messages are generated from `meta` on each read, so switches take effect immediately.
:::

## Next steps [#next-steps]

Start with [Installation](/i18n-error-base/en/installation), then see the flow in [Usage](/i18n-error-base/en/usage). Details are in the [API Reference](/i18n-error-base/en/api).
