diff --git a/src/Antl/index.js b/src/Antl/index.js index eedcd2a..dcf0d72 100644 --- a/src/Antl/index.js +++ b/src/Antl/index.js @@ -108,9 +108,19 @@ class Antl { /** * @see('Formatter.formatMessage') + * + * @throws {InvalidArgumentException} If translation is not found */ formatMessage (key, ...args) { - return this._formatter.formatMessage(this.get(key), ...args) + const rawMessage = this.get(key) + + if (!rawMessage) { + throw GE + .InvalidArgumentException + .invalidParameter(`Missing ${this._locale} translation for key '${key}'`) + } + + return this._formatter.formatMessage(rawMessage, ...args) } /** diff --git a/test/antl.spec.js b/test/antl.spec.js index 9aaf1f7..8c75c25 100644 --- a/test/antl.spec.js +++ b/test/antl.spec.js @@ -45,6 +45,37 @@ test.group('Antl', () => { assert.equal(antl.formatRelative(today.getTime()), 'now') }) + test('format message for a given locale', (assert) => { + const antl = new Antl('en-us', { + 'en-us': { + 'header': { + 'hello': 'Hello {name}' + } + } + }) + + assert.equal(antl.formatMessage('header.hello', { name: 'Peter' }), 'Hello Peter') + }) + + test('format message throws exception when translation is missing', (assert) => { + const antl = new Antl('en-us', { + 'en-us': { + 'validations': { + 'name.required': 'Name is required' + } + }, + '*': { + 'validations': { + 'email.required': 'Email is required' + } + } + }) + + const fn = () => antl.formatMessage('validations.age.required') + + assert.throw(fn, 'E_INVALID_PARAMETER: Missing en-us translation for key \'validations.age.required\'') + }) + test('get message for a key', (assert) => { const antl = new Antl('en-us', { 'en-us': {