在控制器中捕获lib引发的异常

时间:2018-06-12 07:00:26

标签: ruby-on-rails ruby exception

我已将模块保存在lib/rolify_roles.rb

module RolifyRoles
  path = File.join(Rails.root, 'config', 'rolify_roles.yml')
  @config = YAML.load_file(path)

  def add_role(role, target = nil)
    raise "Role is not defined!" if RolifyRoles.config[role].nil?
    ...
  end
end

这个lib由models/user.rb使用add_role方法作为前缀。

然后在controllers/users_controller.rb我有使用add_role方法的方法:

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

      resource = nil
      resource = resource_type.constantize.find(resource_id) unless resource_type.blank? || resource_id.blank?


      respond_to do |format|
        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: @call.errors, status: :unprocessable_entity }
        end
      end

    # Add_role exceptions
    rescue Exception => e
       format.html { render :show }
       format.json { render json: @call.errors, status: :unprocessable_entity }

  end

我试图从控制器方法中的模块RolifyRoles中捕获异常。

但是当引发异常(Role is not defined!)时,它会在模块中结束,并且它不会由控制器处理。 User#add_role lib/rolify_roles.rb, line 31

如何在控制器中处理此行为?

回溯: enter image description here

编辑:

我在控制器中尝试rescue出现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)无法找到记录时,它不会提升rescue块。

 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'

1 个答案:

答案 0 :(得分:0)

我解决了在Why controller does not catch error捕获异常的问题。

respond_to块捕获到异常时,它才能正常工作。