David
David

Reputation: 825

Rails - custom exceptions (errors)

I'm trying to build my own Exception for tagged logging:

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

I'm expecting to be able to call this new exception with:

raise Exceptions::SecurityException "Something security related happened.

The problem is that when I call this I get:

NoMethodError: undefined method 'SecurityException' for Exceptions:Module

Any idea how to correctly raise this error?

Upvotes: 0

Views: 216

Answers (1)

David
David

Reputation: 825

Well, quite easy, you need to raise the instance of the error:

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

or

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

Upvotes: 2

Related Questions