在Ruby on Rails控制器中重构重复的救援异常处理程序

时间:2018-10-24 11:44:14

标签: ruby-on-rails ruby exception-handling refactoring

我在控制器中有两个操作方法,它们具有相同的重复代码,可以挽救两种不同类型的异常:

      def wave
        ...do something here...
      rescue ActionController::ParameterMissing => e
        render :json => {:error => e.message}, :status => 422
      rescue Vendor::ApiError => e
        render :json => {:error => e.message}, :status => 500
      end

      def run
        ...do something different here...
      rescue ActionController::ParameterMissing => e
        render :json => {:error => e.message}, :status => 422
      rescue Vendor::ApiError => e
        render :json => {:error => e.message}, :status => 500
      end

能否将救援处理程序重构为通用的私有方法,并从runwave方法中调用?

2 个答案:

答案 0 :(得分:5)

您可以在控制器中使用rescue_from来挽救所有控制器动作中的错误。你会有类似的东西

class MyController < ApplicationController
  rescue_from ActionController::ParameterMissing do |exception|
    render :json => {:error => exception.message}, :status => 422
  end

  rescue_from Vendor::ApiError do |exception|
    render :json => {:error => exception.message}, :status => 500
  end

  def wave
    # ...
  end

  # ...
end

如果您希望在所有控制器上都具有这种行为,甚至可以将其放在应用程序控制器中(例如,对于挽救ParameterMissing错误可能很有用)

答案 1 :(得分:3)

您可以尝试如下操作:

def wave
  error_handler do
    # ...do something here...
  end
end

def run
  error_handler do
    # ...do something different here...
  end
end

def error_handler
  yield
rescue ActionController::ParameterMissing => e
  render :json => {:error => e.message}, :status => 422
rescue Vendor::ApiError => e
  render :json => {:error => e.message}, :status => 500
end

编辑:但这只是从简单的红宝石角度来看,也许铁轨已经有了一些更好的地方。