Cách dùng
Các thao tác cơ bản như định nghĩa error class, đăng ký thông báo, chuyển ngôn ngữ, prefix và fallback.
Quy trình cơ bản
Định nghĩa error class
Kế thừa I18nErrorBase<TMeta> và định nghĩa thông tin tạo thông báo trong TMeta.
Đăng ký thông báo theo từng ngôn ngữ
Đăng ký thông báo cho từng class và ngôn ngữ bằng setErrorMessage.
Chuyển ngôn ngữ và đọc message
Chuyển bằng setGlobalConfig({ lang }) và đọc 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
Định nghĩa error class
TMeta là thông tin bổ trợ để tạo thông báo. Nó được giữ trong error.meta và truyền cho các hàm đã đăng ký.
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" }
Tham số thứ 2 là chuỗi hoặc hàm (meta) => string. Thứ 3 là { cause } và các option Error khác.
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
Nếu đặt TMeta là undefined, bạn có thể bỏ qua meta.
class NoMetaError extends I18nErrorBase<undefined> {}
const a = new NoMetaError("no meta");
const b = new NoMetaError(undefined, "no meta");
console.log(a.meta); // undefined
Đăng ký thông báo
setErrorMessage đăng ký hàm factory cho từng class và ngôn ngữ.
import { I18nErrorBase, setErrorMessage } from "i18n-error-base";
class TestError extends I18nErrorBase<{ code: string }> {}
setErrorMessage(TestError, ({ code }) => `エラーコード: ${code}`, "ja");
setErrorMessage(TestError, "something went wrong", "en");
Chuỗi cũng được phép. Ngôn ngữ có thể chỉ định dạng mảng.
const message = ({ code }: { code: string }) => `エラーコード: ${code}`;
setErrorMessage(TestError, message, ["ja", "ko", "zh"]);
Đăng ký lại cùng class và ngôn ngữ sẽ ghi đè. Chỉ dùng khi constructor lúc đăng ký và lúc tham chiếu giống nhau, không qua instanceof.
Chuyển ngôn ngữ
Chuyển bằng cài đặt toàn cục của Valibot. message tham chiếu lang hiện tại mỗi lần đọc.
import { setGlobalConfig } from "valibot";
setGlobalConfig({ lang: "ja" });
console.log(error.message); // 日本語の登録メッセージ
setGlobalConfig({ lang: "en" });
console.log(error.message); // 英語の登録メッセージ or 既定メッセージ
lang chưa thiết lập là "en". Ngôn ngữ chưa đăng ký dùng thông báo mặc định của constructor.
setErrorMessage(BusinessRuleError, () => "日本語メッセージ", "ja");
setGlobalConfig({ lang: "fr" });
console.log(error.message); // "Code: ERR, Limit: 50"(既定メッセージ)
Thêm tiền tố
static prefix được thêm vào đầu thông báo đã giải quyết. Áp dụng cho cả bản dịch và mặc định.
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"
Nếu không thiết lập, trả về nguyên văn.
Hành vi dưới dạng Error
error instanceof Error,instanceof I18nErrorBase,instanceofclass cụ thể đều làtrueString(error)/error.toString()bao gồm thông báo đã giải quyết (ví dụ:"Error: ...")causeđược giữ qua{ cause }
Mẫu thường gặp
Cố định thông báo mặc định trong constructor
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);
}
}
Phía gọi chỉ truyền meta, tránh lặp lại văn bản mặc định.
Đăng ký nhiều ngôn ngữ cùng lúc
setErrorMessage(MyError, "エラーが発生しました", ["ja"]);
setErrorMessage(MyError, "An error occurred", ["en", "en-US"]);
Không chuẩn hóa mã ngôn ngữ. "en" và "en-US" là key riêng biệt, hãy đăng ký rõ ràng các mã cần thiết.