Skip to content

Commit

Permalink
Add throwOnError config option
Browse files Browse the repository at this point in the history
... and catch errors during message compilation by default
... and catch errors during message interpolation by default
  • Loading branch information
lephyrus committed Feb 3, 2024
1 parent 1c1ce7b commit 4af1d87
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 5 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
```

Expand Down Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions src/lib/message-format-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface MessageFormatConfig {
strictNumberSign?: boolean;
currency?: string;
strictPluralKeys?: boolean;
throwOnError?: boolean;
}

export const defaultConfig: MessageFormatConfig = {
Expand All @@ -21,4 +22,5 @@ export const defaultConfig: MessageFormatConfig = {
strictNumberSign: false,
currency: "USD",
strictPluralKeys: true,
throwOnError: false,
};
21 changes: 21 additions & 0 deletions src/lib/translate-message-format-compiler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
69 changes: 64 additions & 5 deletions src/lib/translate-message-format-compiler.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -13,7 +16,8 @@ import {
@Injectable()
export class TranslateMessageFormatCompiler extends TranslateCompiler {
private mfCache = new Map<string, MessageFormat>();
private config: MessageFormatOptions<"string">;
private messageFormatOptions: MessageFormatOptions<"string">;
private throwOnError: boolean;

constructor(
@Optional()
Expand All @@ -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 {
Expand All @@ -65,11 +91,44 @@ 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)
);
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
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;
};
}

0 comments on commit 4af1d87

Please sign in to comment.