7

我有一个模块,我在其中执行项目的所有加密/解密任务。我想捕获OpenSSL::Cipher::CipherError此模块中发生的任何异常,以便我可以处理它们。

是否可以做类似的事情

rescue_from OpenSSL::Cipher::CipherError, :with => :cipher_error

在模块内部?

4

1 回答 1

8

我进行了一些调查并提出了解决方案。您说您有一个模块可以在其中进行加密。我猜那个模块代表一个单例。但是,我的解决方案需要您有一个实例。

class Crypto
   def self.instance
      @__instance__ ||= new
   end
end

提取模块中的加密行为。

module Encryptable
   def encrypt
      # ...
   end

   def decrypt
      # ...
   end
end

创建一个处理异常的新模块。

module ExceptionHandler
  extend ActiveSupport::Concern

  included do
    include ActiveSupport::Rescuable
    rescue_from StandardError, :with => :known_error
  end

  def handle_known_exceptions
     yield
  rescue => ex
     rescue_with_handler(ex) || raise
  end

  def known_error(ex)
    Rails.logger.error "[ExceptionHandler] Exception #{ex.class}: #{ex.message}"
  end
end

所以现在你可以handle_known_exceptions在你的Crypto. 这不是很方便,因为你没有得到太多。您仍然必须在每个方法中调用异常处理程序:

class Crypto
  include ExceptionHandler

  def print_bunnies
    handle_known_exceptions do
      File.open("bunnies")
    end
  end
end

如果我们定义一个为我们执行此操作的委托者,则无需执行此操作:

class CryptoDelegator
  include ExceptionHandler

  def initialize(target)
    @target = target
  end

  def method_missing(*args, &block)
    handle_known_exceptions do
      @target.send(*args, &block)
    end
  end
end

完全覆盖 , 的初始化Crypto以使用委托器。

class Crypto
  include Encryptable

  def self.new(*args, &block)
    CryptoDelegator.new(super)
  end

  def self.instance
      @__instance__ ||= new
  end
end

就是这样!

于 2013-06-14T10:14:16.183 回答