如何挽救 Rails 模板(ERB 文件)中的错误

abs*_*ive 5 ruby ruby-on-rails

我有一个 ERB 模板,它有一些来自其他 gems 的辅助方法

sample.html.erb

<h1>All The Stuff</h1>
<% all_the_stuff.each do |stuff| %>
  <div><%= stuff %></div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

lib/random_file.rb

def all_the_stuff
   if ALL_THE_STUFF.exists?
      ALL_THE_STUFF
   else
      fail AllTheStuffException
   end
end
Run Code Online (Sandbox Code Playgroud)

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

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

小智 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 %>
Run Code Online (Sandbox Code Playgroud)

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