From c46115268a04d20607e968ed8f93ce57bcd584e5 Mon Sep 17 00:00:00 2001 From: Timofei Iatsenko Date: Sat, 21 Dec 2024 14:53:47 +0100 Subject: [PATCH] feat: add meaningful error when locale is not set --- packages/core/src/i18n.test.ts | 13 +++++++++++++ packages/core/src/i18n.ts | 8 ++++++++ 2 files changed, 21 insertions(+) diff --git a/packages/core/src/i18n.test.ts b/packages/core/src/i18n.test.ts index 4e64511e4..34e132dc3 100644 --- a/packages/core/src/i18n.test.ts +++ b/packages/core/src/i18n.test.ts @@ -431,4 +431,17 @@ describe("I18n", () => { expect(i18n._("Software development")).toEqual("Software­entwicklung") expect(i18n._("Software development")).toEqual("Software­entwicklung") }) + + it("._ should throw a meaningful error when locale is not set", () => { + const i18n = setupI18n({}) + expect(() => + i18n._( + "Text {0, plural, offset:1 =0 {No books} =1 {1 book} other {# books}}" + ) + ).toThrowErrorMatchingInlineSnapshot(` + "Lingui: Attempted to call a translation function without setting a locale. + Make sure to call \`i18n.activate(locale)\` before using Lingui functions. + This issue may also occur due to a race condition in your initialization logic." + `) + }) }) diff --git a/packages/core/src/i18n.ts b/packages/core/src/i18n.ts index afcb7b640..a133b7cf2 100644 --- a/packages/core/src/i18n.ts +++ b/packages/core/src/i18n.ts @@ -240,6 +240,14 @@ export class I18n extends EventEmitter { values?: Values, options?: MessageOptions ): string { + if (!this.locale) { + throw new Error( + "Lingui: Attempted to call a translation function without setting a locale.\n" + + "Make sure to call `i18n.activate(locale)` before using Lingui functions.\n" + + "This issue may also occur due to a race condition in your initialization logic." + ) + } + let message = options?.message if (!id) {