How do you rescue I18n::MissingTranslationData?

坚强是说给别人听的谎言 提交于 2020-01-01 17:00:33

问题


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?


回答1:


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)




回答2:


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



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/6027471/how-do-you-rescue-i18nmissingtranslationdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!