【问题标题】:Translation of ActionController error messages with I18n使用 I18n 翻译 ActionController 错误消息
【发布时间】:2013-12-13 23:01:59
【问题描述】:

I18n 有问题。我找不到正确的方法来翻译 ActionController 错误消息,例如

The action '...' could not be found for ...Controller

我在此存储库中的任何示例文件中都找不到翻译:https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml

我找到了验证错误等的解决方案,但不是针对此类错误。

是否可以用 I18n 文件翻译这种错误消息?

更新:我想翻译它们,因为它们显示给用户。我在这个 railscast 中做到了:http://railscasts.com/episodes/53-handling-exceptions-revised

所有异常都由 railsapp 本身处理,而不是通过具有此配置的 middelware:

config.exceptions_app = self.routes

然后所有异常都被路由到一个动作:

match '(errors)/:status', to: 'errors#show', constraints: {status: /\d{3}/} # via: :all

在此操作中,错误消息由变量使用:

def show
  @exception = env["action_dispatch.exception"]
  respond_to do |format|
    format.html { render action: request.path[1..-1] }
    format.json { render json: {status: request.path[1..-1], error: @exception.message} }
  end
end

这个变量然后显示在生产视图中:

<h1>Forbidden.</h1>
<% if @exception %>
  <p><%= @exception.message %></p>
<% else %>
  <p>You are not authorized to perform that action.</p>
<% end %>

现在错误消息是动态的。我认为总的来说这是一件好事,因为用户可以获得更多信息,哪些地方出了问题,以及如何避免特定错误。但这信息有点太多了。我不希望他们看到例如哪个控制器处理了该操作。因此,我想将错误消息“翻译”为更安全的变体。

【问题讨论】:

  • 为什么要翻译这个错误?它们仅用于开发。当您在生产模式下运行应用程序时,此错误将替换为 505 或 404 页面,最终用户不会看到它们。
  • 我想翻译它们,因为它们显示给用户。我在这个 railscast 中像 Ryan Bates 一样做到了:railscasts.com/episodes/53-handling-exceptions-revised,所有错误都被路由到单个操作。我会用这些信息更新我的问题。

标签: ruby-on-rails error-handling internationalization rails-i18n


【解决方案1】:

您可以使用异常类名称作为I18n 翻译的键。这样,您可以在翻译文件中使用异常类名称(本质上是异常),然后为特定异常使用您自己的话。

I18n.t(@exception.class.name.underscore, default: "Generic Error")

【讨论】:

  • 你知道如何捕捉动作吗?我能够显示“找不到 URL ”吗?
  • 我认为最好的办法是使用正则表达式来解析异常消息。
猜你喜欢
  • 2018-06-10
  • 2021-02-28
  • 2018-02-16
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多