ruby-on-rails - 在 Ruby on Rails Controller 中重构重复的救援异常处理程序

标签 ruby-on-rails ruby exception refactoring

我在一个 Controller 中有两个操作方法,它们具有相同的重复代码来挽救两种不同类型的异常:

      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

是否可以将救援处理程序重构为一个通用的私有(private)方法,并从 runwave 方法中调用?

最佳答案

您可以使用 rescue_from在你的 Controller 中从所有 Controller 操作中的错误中解救出来。你会有这样的东西

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

如果您希望在所有 Controller 上都有这种行为,您甚至可以将它放在您的应用程序 Controller 中(例如,可能有助于挽救 ParameterMissing 错误)

关于ruby-on-rails - 在 Ruby on Rails Controller 中重构重复的救援异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52968156/

相关文章:

ruby-on-rails - 处理 Net::HTTP.get 失败

ruby-on-rails - 如何在 Rails 中为不同的用户建模

Ruby 的 vcr 的 Java 替代品?

java - 使用 Eclipse 调试 Java : process is suspended, 但它不会抛出任何异常

ruby-on-rails - 在 Rails 3 中对关联模型进行排序?

ruby-on-rails - 使用 ruby​​ on Rails 向静态网站添加功能

ruby-on-rails - Gem::LoadError:为数据库适配器指定了 'sqlite3',但未加载 gem

ruby - 从命令行使用 bundler 将 gem 添加到 gemfile

android - 媒体播放器异常

c++ - 在 NTL 中捕获 InvMod 错误