fix: crash if message has syntax error (#128)

* fix crash if message has syntax error

* fix custom number format test & lint require error

Co-authored-by: Ivan Chalyk <boomfly@boomfly-pro.local>
This commit is contained in:
Ivan Chalyk 2021-02-15 22:36:28 +06:00 committed by GitHub
parent 8ad5250f71
commit 0d623f9884
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 6 deletions

View File

@ -67,7 +67,18 @@ const formatMessage: MessageFormatter = (id, options = {}) => {
return message;
}
return getMessageFormatter(message, locale).format(values) as string;
let result = message;
try {
result = getMessageFormatter(message, locale).format(values) as string;
} catch (e) {
console.warn(
`[svelte-i18n] Message with "${id}" has syntax error:`,
e.message,
);
}
return result;
};
const formatTime: TimeFormatter = (t, options) => {

View File

@ -7,6 +7,8 @@ import {
locale,
} from '../../../src/runtime';
const formatsJson = require('../../fixtures/formats.json');
beforeEach(() => {
init({ fallbackLocale: undefined });
});
@ -35,7 +37,7 @@ describe('number formatter', () => {
it('formats a number with a custom format', () => {
init({
fallbackLocale: 'en',
formats: require('../../fixtures/formats.json'),
formats: formatsJson,
});
expect(getNumberFormatter({ format: 'brl' }).format(number)).toBe(
@ -81,7 +83,7 @@ describe('date formatter', () => {
it('throws if passed a non-existing format', () => {
init({
fallbackLocale: 'en',
formats: require('../../fixtures/formats.json'),
formats: formatsJson,
});
expect(() =>
@ -92,7 +94,7 @@ describe('date formatter', () => {
it('formats a date with a custom format', () => {
init({
fallbackLocale: 'en',
formats: require('../../fixtures/formats.json'),
formats: formatsJson,
});
expect(getDateFormatter({ format: 'customDate' }).format(date)).toBe(
@ -138,7 +140,7 @@ describe('time formatter', () => {
it('formats a time with a custom format', () => {
init({
fallbackLocale: 'en',
formats: require('../../fixtures/formats.json'),
formats: formatsJson,
});
expect(getTimeFormatter({ format: 'customTime' }).format(time)).toBe(
@ -149,7 +151,7 @@ describe('time formatter', () => {
it('throws if passed a non-existing format', () => {
init({
fallbackLocale: 'en',
formats: require('../../fixtures/formats.json'),
formats: formatsJson,
});
expect(() =>
@ -189,6 +191,7 @@ describe('message formatter', () => {
});
it('formats number with custom formats', () => {
locale.set('en');
expect(
getMessageFormatter('Number: {n, number, compactShort}', 'en').format({
n: 2000000,