Skip to content

Commit

Permalink
i18n: Log errors max single time per message (#5481)
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth authored Mar 14, 2018
1 parent 530a66e commit 817c0e0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
22 changes: 12 additions & 10 deletions i18n/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,19 @@
* External dependencies
*/
import Jed from 'jed';
import memoize from 'memize';

let i18n;

/**
* Log to console, once per message; or more precisely, per referentially equal
* argument set. Because Jed throws errors, we log these to the console instead
* to avoid crashing the application.
*
* @param {...*} args Arguments to pass to `console.error`
*/
const logErrorOnce = memoize( console.error ); // eslint-disable-line no-console

/**
* Merges locale data into the Jed instance by domain. Creates a new Jed
* instance if one has not yet been assigned.
Expand Down Expand Up @@ -59,11 +69,7 @@ export function dcnpgettext( domain = 'default', context, single, plural, number
try {
return getI18n().dcnpgettext( domain, context, single, plural, number );
} catch ( error ) {
// Disable reason: Jed throws errors. To avoid crashing the application
// we log these to the console instead, and return a default value.

// eslint-disable-next-line no-console
console.error( 'Jed localization error: \n\n' + error.toString() );
logErrorOnce( 'Jed localization error: \n\n' + error.toString() );

return single;
}
Expand Down Expand Up @@ -150,11 +156,7 @@ export function sprintf( format, ...args ) {
try {
return Jed.sprintf( format, ...args );
} catch ( error ) {
// Disable reason: Jed throws errors. To avoid crashing the application
// we log these to the console instead, and return a default value.

// eslint-disable-next-line no-console
console.error( 'Jed sprintf error: \n\n' + error.stack );
logErrorOnce( 'Jed sprintf error: \n\n' + error.toString() );

return format;
}
Expand Down
4 changes: 4 additions & 0 deletions i18n/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
*/
import { dcnpgettext, sprintf } from '../';

// Mock memoization as identity function. Inline since Jest errors on out-of-
// scope references in a mock callback.
jest.mock( 'memize', () => ( fn ) => fn );

describe( 'i18n', () => {
describe( 'dcnpgettext()', () => {
it( 'absorbs errors', () => {
Expand Down

0 comments on commit 817c0e0

Please sign in to comment.