【问题标题】:Why does this rescue syntax work?为什么这种救援语法有效?
【发布时间】:2012-04-10 12:53:51
【问题描述】:

好的,所以我有我正在使用的应用程序的这种方法,它可以在生产中使用。我的问题为什么会这样?这是新的 Ruby 语法吗?

def edit
  load_elements(current_user) unless current_user.role?(:admin)

  respond_to do |format|
    format.json { render :json => @user }   
    format.xml  { render :xml => @user }
    format.html
  end

rescue ActiveRecord::RecordNotFound
  respond_to_not_found(:json, :xml, :html)
end

【问题讨论】:

标签: ruby rescue


【解决方案1】:

rescues 在方法中时不需要绑定到显式的begin,这正是定义语法的方式。例如,请参阅#19 herethis SO question,以及the dupe above

【讨论】:

    【解决方案2】:

    rescue 可以单独行动。不需要总是开始和结束。

    当在线上的其他事情出错时,您可以使用rescue 以单行形式返回一个值:

    h = { :age => 10 }
    h[:name].downcase                         # ERROR
    h[:name].downcase rescue "No name"  
    

    【讨论】:

    • 不过,这将其用作语句修饰符,这不是 OP 的问题。当然,您是对的,但它并不能直接回答问题。
    【解决方案3】:

    rescue 单词是方法定义的一部分

    但在控制器中最好使用rescue_from 来挽救错误

    【讨论】:

      【解决方案4】:

      试试这个

      def edit
        begin
          load_elements(current_user) unless current_user.role?(:admin)
      
          respond_to do |format|
            format.json { render :json => @user }   
            format.xml  { render :xml => @user }
            format.html
          end
      
        rescue ActiveRecord::RecordNotFound
          respond_to_not_found(:json, :xml, :html)
        end
      end
      

      【讨论】:

      • 在方法定义中使用rescue(以及隐含的begin)是完全合法的,而没有显式的begin
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 2023-03-03
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多