Rails - 自定义异常(错误)

时间:2017-12-07 09:42:40

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

我正在尝试为标记日志记录构建自己的Exception

module Exceptions
  class GeneralException < StandardError
    LOGGER_NAME = 'Base'

    def initialize(message)
      @logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
      @logger.tagged(get_logger_name) { @logger.error message }
      @message = message
    end

    def get_logger_name
      self.class::LOGGER_NAME
    end
  end

  class InvalidDataException < GeneralException; end

  class SecurityException < GeneralException
    LOGGER_NAME = 'Security'
  end

  class ElasticSearchException < GeneralException
    LOGGER_NAME = 'Elastic'
  end
end

我希望能够通过以下方式调用此新例外:

raise Exceptions::SecurityException "Something security related happened.

问题在于,当我打电话给我时,我得到:

  

NoMethodError:未定义的方法&#39; SecurityException&#39;例外:模块

知道如何正确引发此错误吗?

1 个答案:

答案 0 :(得分:1)

嗯,很简单,你需要提出错误的实例:

mPaint.typeface=TypefaceCompat.createFromResourcesFamilyXml(...)

 raise Exceptions::SecurityException.new "Something security related happend."