Skip to content

Commit

Permalink
fix: crash if message has syntax error (#128)
Browse files Browse the repository at this point in the history
* fix crash if message has syntax error

* fix custom number format test & lint require error

Co-authored-by: Ivan Chalyk <boomfly@boomfly-pro.local>
  • Loading branch information
boomfly and Ivan Chalyk committed Feb 15, 2021
1 parent 8ad5250 commit 0d623f9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
13 changes: 12 additions & 1 deletion src/runtime/stores/formatters.ts
Expand Up @@ -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) => {
Expand Down
13 changes: 8 additions & 5 deletions test/runtime/includes/formatters.test.ts
Expand Up @@ -7,6 +7,8 @@ import {
locale,
} from '../../../src/runtime';

const formatsJson = require('../../fixtures/formats.json');

beforeEach(() => {
init({ fallbackLocale: undefined });
});
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(() =>
Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand All @@ -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(() =>
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 0d623f9

Please sign in to comment.