From 4af1d8734e88ecfe67a8e56b0541a00475fe5e0d Mon Sep 17 00:00:00 2001 From: Lukas Rieder <1394536+lephyrus@users.noreply.github.com> Date: Sat, 3 Feb 2024 22:52:09 +0100 Subject: [PATCH] Add `throwOnError` config option ... and catch errors during message compilation by default ... and catch errors during message interpolation by default --- README.md | 10 +++ src/lib/message-format-config.ts | 2 + .../translate-message-format-compiler.spec.ts | 21 ++++++ src/lib/translate-message-format-compiler.ts | 69 +++++++++++++++++-- 4 files changed, 97 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index c2ac6df..c3340bc 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ You can override the values used when configuring MessageFormat by providing a c strictNumberSign: false, currency: "USD", strictPluralKeys: true + throwOnError: false } ``` @@ -101,6 +102,15 @@ Here's two important differences to _ngx-translate_'s default syntax when using - You lose the ability to access object properties in your placeholders: `'Hello {name.first} {name.last}'` won't work. - Simple placeholders are enclosed in single curly braces instead of double curly braces: `Hello {name}` +### Debugging + +There are two stages in the translation process: + +1. Compiling the message (e.g. `Hello {name}`) to a function: this fails if the MessageFormat syntax is incorrect, for example. +2. Interpolating parameters (e.g. using `Linda` as the name in the above message): this fails if the parameters don't "fit" the message. + +By default, the errors that get thrown in these two stages are caught and logged to the console, and the original message is returned as the translation. If you do not want this behaviour, pass `throwOnError: true` in `MESSAGE_FORMAT_CONFIG` (see above). (Note that this may make all translations fail if there's a syntax error in any message.) + This library also exports `TranslateMessageFormatDebugCompiler`, which you can use as a drop-in replacement for the regular `TranslateMessageFormatCompiler`. The debug compiler will log to the console whenever a translation string is compiled to an interpolation function, and whenever such a function is called (with interpolation parameters) to compute the final translated string. The logs may help you figuring out which translation produces an error and the timing of when the individual steps happen. diff --git a/src/lib/message-format-config.ts b/src/lib/message-format-config.ts index 5fe9c42..875804d 100644 --- a/src/lib/message-format-config.ts +++ b/src/lib/message-format-config.ts @@ -13,6 +13,7 @@ export interface MessageFormatConfig { strictNumberSign?: boolean; currency?: string; strictPluralKeys?: boolean; + throwOnError?: boolean; } export const defaultConfig: MessageFormatConfig = { @@ -21,4 +22,5 @@ export const defaultConfig: MessageFormatConfig = { strictNumberSign: false, currency: "USD", strictPluralKeys: true, + throwOnError: false, }; diff --git a/src/lib/translate-message-format-compiler.spec.ts b/src/lib/translate-message-format-compiler.spec.ts index d58d2b4..5d079cd 100644 --- a/src/lib/translate-message-format-compiler.spec.ts +++ b/src/lib/translate-message-format-compiler.spec.ts @@ -127,6 +127,27 @@ describe("TranslateMessageFormatCompiler", () => { "3 pies" ); }); + + it("should respect passed-in throwOnError value", () => { + compiler = new TranslateMessageFormatCompiler(); + + const illegalMsg = "gimme {sweet"; + const legalMsg = "gimme {sweet}"; + + expect(compiler.compile(illegalMsg, "en")({ sweet: "cookie" })).toBe( + "gimme {sweet" + ); + expect(compiler.compile(legalMsg, "en")(null)).toBe("gimme {sweet}"); + + compiler = new TranslateMessageFormatCompiler({ throwOnError: true }); + + expect(() => compiler.compile(illegalMsg, "en")).toThrowError( + /Unexpected message end/ + ); + expect(() => compiler.compile(legalMsg, "en")(null)).toThrowError( + /Cannot read properties of null/ + ); + }); }); describe("compile", () => { diff --git a/src/lib/translate-message-format-compiler.ts b/src/lib/translate-message-format-compiler.ts index 026d54b..b6c61b6 100644 --- a/src/lib/translate-message-format-compiler.ts +++ b/src/lib/translate-message-format-compiler.ts @@ -1,6 +1,9 @@ import { Inject, Injectable, Optional } from "@angular/core"; import { TranslateCompiler } from "@ngx-translate/core"; -import MessageFormat, { MessageFormatOptions } from "@messageformat/core"; +import MessageFormat, { + MessageFormatOptions, + MessageFunction, +} from "@messageformat/core"; import { defaultConfig, MessageFormatConfig, @@ -13,7 +16,8 @@ import { @Injectable() export class TranslateMessageFormatCompiler extends TranslateCompiler { private mfCache = new Map(); - private config: MessageFormatOptions<"string">; + private messageFormatOptions: MessageFormatOptions<"string">; + private throwOnError: boolean; constructor( @Optional() @@ -28,22 +32,44 @@ export class TranslateMessageFormatCompiler extends TranslateCompiler { strictNumberSign: strict, currency, strictPluralKeys, + throwOnError, } = { ...defaultConfig, ...config, }; - this.config = { + this.messageFormatOptions = { customFormatters, biDiSupport, strict, currency, strictPluralKeys, }; + this.throwOnError = !!throwOnError; } public compile(value: string, lang: string): (params: any) => string { - return this.getMessageFormatInstance(lang).compile(value); + let result: MessageFunction<"string">; + + try { + result = this.getMessageFormatInstance(lang).compile(value); + } catch (err) { + if (this.throwOnError) { + throw err; + } + + console.error(err); + console.error( + `[ngx-translate-messageformat-compiler] Could not compile message for lang '${lang}': '${value}'. Translation will not work.` + ); + result = compileFallback(value, lang); + } + + if (!this.throwOnError) { + result = wrapInterpolationFunction(result, value); + } + + return result; } public compileTranslations(translations: any, lang: string): any { @@ -65,7 +91,7 @@ export class TranslateMessageFormatCompiler extends TranslateCompiler { if (!this.mfCache.has(locale)) { this.mfCache.set( locale, - new MessageFormat<"string">(locale, this.config) + new MessageFormat<"string">(locale, this.messageFormatOptions) ); } @@ -73,3 +99,36 @@ export class TranslateMessageFormatCompiler extends TranslateCompiler { return this.mfCache.get(locale)!; } } + +function wrapInterpolationFunction( + fn: MessageFunction<"string">, + message: string +): MessageFunction<"string"> { + return (params: any) => { + let result: string = message; + + try { + result = fn(params); + } catch (err) { + console.error(err); + console.error( + `[ngx-translate-messageformat-compiler] Could not interpolate '${message}' with params '${params}'. Translation will not work.` + ); + } + + return result; + }; +} + +function compileFallback( + message: string, + lang: string +): MessageFunction<"string"> { + return () => { + console.warn( + `[ngx-translate-messageformat-compiler] Falling back to original invalid message: '${message}' ('${lang}')` + ); + + return message; + }; +}