【问题标题】:Catch exception raised by lib in controller在控制器中捕获 lib 引发的异常
【发布时间】:2018-06-12 07:00:26
【问题描述】:

我有模块保存在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

这个库是由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

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

回溯:

编辑:

我尝试在控制器中从 RecordNotFound rescue 出错,如下所示:

  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'

【问题讨论】:

  • 首先,don't rescue Exception。二、create_user_role方法中是否有begin关键字?
  • 我使用Exception只是因为测试。现在begin关键字不用了,但是我用关键字试了一下,结果是一样的。
  • 您可能需要显示整个create_user_role 方法。
  • @MarekLipka 我认为这里不需要begin,例如def foo; rescue; end 工作正常。另外,简,我不明白你为什么会出现这种行为。是的,请展示整个方法。
  • @maxpleaner 我没说需要,我问有没有。

标签: ruby-on-rails ruby exception


【解决方案1】:

我在那里解决了捕获异常Why controller does not catch error。

当在respond_to 块中捕获到异常时,它会正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多