【问题标题】:Rails - custom exceptions (errors)Rails - 自定义异常(错误)
【发布时间】:2017-12-07 09:42:40
【问题描述】:

我正在尝试构建自己的 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: 异常的未定义方法“SecurityException”:模块

知道如何正确地引发这个错误吗?

【问题讨论】:

  • SecurityException 不是一种方法。这是一堂课。你需要先实例化它,传入消息。

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


【解决方案1】:

嗯,很简单,你需要引发错误的实例:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多