Rails - 自定义异常(错误)

Rails - custom exceptions (errors)

我正在尝试构建自己的 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: undefined method 'SecurityException' for Exceptions:Module

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

好吧,很简单,您需要提出错误实例:

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

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