3

I want to be able to rescue I18n::MissingTranslationData like so:

begin
  value = I18n.t('some.key.that.does.not.exist')
  puts value
  return value if value
rescue I18n::MissingTranslationData
  puts "Kaboom!"
end

I tried the above, but it doesn't seem to go into the rescue block. I just see, on my console (because of puts): translation missing: some.key.that.does.not.exist. I never see Kaboom!.

How do I get this to work?

Ramon Tayag
  • 15,224
  • 9
  • 43
  • 69

5 Answers5

6

IMO, it's pretty strange but in the current version of i18n (0.5.0) you should pass an exception that you want to rescue:

require 'i18n'
begin
  value = I18n.translate('some.key.that.does.not.exist', :raise => I18n::MissingTranslationData)
  puts value
  return value if value
rescue I18n::MissingTranslationData
  puts "Kaboom!"
end

and it will be fixed in the future 0.6 release (you can test it - https://github.com/svenfuchs/i18n)

Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
5

Same as above but nicer.

v = "doesnt_exist"
begin
  puts I18n.t "langs.#{v}", raise: true
rescue
  puts "Nooo #{v} has no Translation!"
end

or

puts I18n.t("langs.#{v}", default: "No Translation!")

or

a = I18n.t "langs.#{v}", raise: true rescue false
unless a
  puts "Update your YAML!"
end
Fer Padron
  • 189
  • 2
  • 3
0

In the current version of I18n, the exception you're looking for is actually called MissingTranslation. The default exception handler for I18n rescues it silently, and just passes it up to ArgumentError to print an error message and not much else. If you actually want the error thrown, you'll need to override the handler.

See the source code for i18n exceptions, and section 6.2 of RailsGuides guide to I18n for how to write a custom handler

danieltahara
  • 4,743
  • 3
  • 18
  • 20
  • Instead of saying current version, please be specific. Same thing with you source code link: please link to a specific revision instead of master. – Andy Stewart Sep 23 '16 at 16:34
0

Note that now you simply pass in :raise => true

assert_raise(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }

...which will raise I18n::MissingTranslationData.

See https://github.com/svenfuchs/i18n/blob/master/lib/i18n/tests/lookup.rb

andrewhao
  • 56
  • 2
0

This should do the job. When using rescue I would always catch specific errors. using rescue without a specific error can lead to unexpected behaviour.


require 'i18n'
begin
  value = I18n.t 'some.key.that.does.not.exist', raise: true
  puts value
rescue I18n::MissingTranslationData
  puts "Kaboom!"
end