在rails控制器的before_action中捕获所有异常

时间:2014-04-08 14:32:44

标签: ruby-on-rails

albums_controller.rb:

lass AlbumsController < ApplicationController
  before_action :set_album, only: [:show, :edit, :update, :destroy]

  def destroy
    if @album.destroy
      redirect_to albums_url, notice: 'Album was successfully destroyed.'
    else
      redirect_to albums_url, error: 'Album destroy failed.' # _DEST_
    end
  end

 private
    def set_album
      @album = Album.find(params[:id]) # _FIND_
    end
end

我想抓住Album.find()的异常。根据{{​​3}}我添加了:

  rescue_from Exception, with: :flash_error

  # private
  def flash_error
      flash_message :error, 'Something went wrong..' # _FLASH_
  end

我将上面的部分标记为_FIND__FLASH__DEST_,我想按顺序浏览所有部分。我试图删除不存在的专辑来触发它。我得到了包含相册/(:id)的URL的空白页面(我试图删除的那个)所以我想我一直停留在_FLASH_部分。

我应该怎么做才能调用destroy动作(我的意思是原来的一个叫做rescue_form,因为它可以捕获其他控制器动作的其他异常)。如何才能获得比Something went wrong更好的消息?

主要目标是重定向到正确的页面(在_DEST_指定),所以也许有更好的方法。

1 个答案:

答案 0 :(得分:2)

&#34; rescue_from&#34;回调方法&#34; flash_error&#34;表现得像一个普通的控制器动作,从用户的角度来看最终呈现空白页面。从那个意义上讲,它并没有停留在那里,而是在那里完成。

为了&#34;继续&#34;你需要重定向或渲染。请注意,异常会被传播,因此您可以获得有关所发生情况的更多详细信息:

 #I am using Rails 3.2 flash notation
 def flash_error(exception)
    flash[:error] = "#{exception.message} (Something went wrong..)" # _FLASH_
    redirect_to albums_url
 end

我的建议是永远不要抓住所有例外情况。根据我的经验,除了悲伤之外什么都没有。想象一下,如果你在索引操作中有异常 - 那最终将会循环。