Skip to content

Commit

Permalink
refactor(formatMessage): raise meaningful exception
Browse files Browse the repository at this point in the history
* Adding spec for Antl.formatMessage

* Throwing exception on Antl.formatMessage when translation key is missing
  • Loading branch information
viniciusoyama authored and thetutlage committed Mar 20, 2019
1 parent e54c93f commit 0b22a04
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Antl/index.js
Expand Up @@ -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)
}

/**
Expand Down
31 changes: 31 additions & 0 deletions test/antl.spec.js
Expand Up @@ -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': {
Expand Down

0 comments on commit 0b22a04

Please sign in to comment.