【问题标题】:Why controller does not catch error为什么控制器不捕获错误
【发布时间】:2018-11-21 21:30:15
【问题描述】:

我试图从控制器中的 RecordNotFound 错误中解救出来:

  def create_user_role
    authorize User
    role = params[:user][:rolify_role].to_sym
    resource_type = params[:user][:resource_type]
    resource_id = params[:user][:id]

    # Catch RecordNotFound doesn't work
    begin
      resource = nil
      resource = resource_type.constantize.find(resource_id) if RolifyRoles.available_resources.include?(resource_type) && resource_id.present?
    rescue ActiveRecord::RecordNotFound => e
      format.html { render :show }
      flash[:error] = e.message
    end
  end

resource_type.constantize.find(resource_id) 找不到记录时,它不会被救援块捕获。

 Completed 500 Internal Server Error in 46ms (ActiveRecord: 3.2ms)
 ActiveRecord::RecordNotFound - Couldn't find RequestComment with 'id'=1:
 app/controllers/users_controller.rb:58:in `create_user_role'

我尝试用StandardError 甚至Exception 进行救援,结果是一样的。

问题出在哪里?

我还从我的module 调用了一个方法,该方法引发了一些异常,这些异常也没有得到处理。

回溯:

07:23:29 web.1     | Started POST "/users/kru0096/create_user_role" for 10.0.131.29 at 2018-06-13 07:23:29 +0200
07:23:39 web.1     | Processing by UsersController#create_user_role as HTML
07:23:39 web.1     |   Parameters: {"utf8"=>"✓", "authenticity_token"=>"5kN6MuoP4YntbTvL5cTDPuCZypDdO
o1KPcvIu8dJ6otX0aYPwuWg64/TTTgDe6DRXn6wCs1KvgT9xjkr9g/dyA==", "user"=>{"rolify_role"=>"hoac", "resource_type"=>"RequestComment", "id"=>"1"}, "commit"=>"", "id"=>"kru0096"}
07:23:39 web.1     |   User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
07:23:39 web.1     |   User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`login` = 'kru0096' LIMIT 1
07:23:39 web.1     |   RequestComment Load (0.3ms)  SELECT  `request_comments`.* FROM `request_comments` WHERE `request_comments`.`id` = 1 LIMIT 1
07:23:39 web.1     | Completed 500 Internal Server Error in 41ms (ActiveRecord: 6.5ms)
07:23:39 web.1     | 
07:23:39 web.1     | 
07:23:39 web.1     | 
07:23:39 web.1     | ActiveRecord::RecordNotFound - Couldn't find RequestComment with 'id'=1:
07:23:39 web.1     |   app/controllers/users_controller.rb:92:in `create_user_role'
07:23:39 web.1     | 

【问题讨论】:

  • 你在哪里写了rescue_from?在 ApplicationController 中?
  • 错误发生在您的begin..rescue 块之外很可能出现在authorize User
  • rescue_from 未在任何地方定义。 @engineersmnky - resource_type.constantize.find 抛出错误
  • 移动开始到上面授权还是不解救吗?
  • 结果还是一样

标签: ruby-on-rails ruby exception controller


【解决方案1】:

看起来它正确地捕获了错误,我想知道真正的问题是否是救援语句中代码的顺序。尝试在渲染调用之前设置闪光灯。

rescue ActiveRecord::RecordNotFound => e
  flash[:error] = e.message
  format.html { render :show }
end

对我来说,看起来您返回的是 error.message 而不是渲染语句。同样,你也可以试试render :show, flash: { error: e.message }

【讨论】:

  • 我试过了,但还是发生了异常,rescue 块没有被使用。
  • 我在问题中添加了回溯。
  • 是整个回溯吗? 500 内部服务器错误基本上意味着 rails 不知道如何处理它收到的错误。您还可以尝试在ActiveRecord::RecordNotFound 上添加rescue_from 语句以尝试捕获此错误 - medium.com/spritle-software/… api.rubyonrails.org/classes/ActiveSupport/Rescuable/…
  • 我试过rescue_from语句,结果是一样的。我更改了控制器方法,在 respond_to 块中定义了救援,现在 catch 可以正常工作了。
【解决方案2】:

当在respond_to 块中捕获异常时,异常处理开始工作。

我也定义了自己的异常,但这对结果没有影响。

def create_user_role
    authorize User
    # Params Inicialization
    role = params[:user][:rolify_role].to_sym
    resource_type = params[:user][:resource_type]
    resource_id = params[:user][:id]

    respond_to do |format|
      begin
        # Make resource as instance of class or set to nil
        resource = RolifyRoles.build_resource(resource_type, resource_id)
        if @user.add_role role, resource
          format.html { redirect_to @user, notice: "Role #{role} was successfully added." }
          format.json { render :show, status: :created, location: @user }
        else
          format.html { render :show }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      # Catch self defined exceptions
      rescue RolifyRolesException => e
        flash[:error] = e.message
        flash.keep
        format.html { render :show, flash: { error: e.message } }
        format.json { render json: e.message, status: :unprocessable_entity }
      end
    end
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多