【问题标题】:How to to rescue from errors in a Rails template (ERB file)如何挽救 Rails 模板(ERB 文件)中的错误
【发布时间】:2016-08-01 20:11:45
【问题描述】:

我有一个 ERB 模板,其中包含一些来自其他 gem 的辅助方法

sample.html.erb

<h1>All The Stuff</h1>
<% all_the_stuff.each do |stuff| %>
  <div><%= stuff %></div>
<% end %>

lib/random_file.rb

def all_the_stuff
   if ALL_THE_STUFF.exists?
      ALL_THE_STUFF
   else
      fail AllTheStuffException
   end
end

现在,如果 ALL_THE_STUFF 不存在,我会得到一个 ActionView::Template::Error。但是,在控制器级别的异常处理不会被捕获。 在控制器的情况下,我使用rescue_from 挽救ApplicationController 中的异常。有没有一个地方可以存放我所有的 ERB 模板?

如何处理在模板中捕获的异常(不是由于控制器代码)?

【问题讨论】:

  • begin...rescue...end 在 ERB 中工作得很好。
  • 我应该更清楚。对于我的应用程序控制器,我可以执行 rescue_from 块来救援,但没有这样的地方可以为所有模板执行此操作。
  • 你应该能够以同样的方式做到这一点:rescue_from ActionView::Template::Error, with: :your_method_here

标签: ruby-on-rails ruby


【解决方案1】:

我认为更好的解决方案如下:

class ThingsController < ApplicationController
  def sample
    @things = Thing.all
  end
end


# views/things/sample.html.erb
<h1>All The Things</h1>
<% if @things.present? %>
  <% @things.each do |thing| %>
    <div><%= thing %></div>
  <% end %>
<% else %>
  There are no things at the moment.
<% end %>

这是 rails 方式,避免使用任何 Exception 类作为控制流,这通常是个坏主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多