Search code examples
ruby-on-railscustom-errorscustom-error-handling

Rails 4, How to have a callback to a custom error?


Below are some sudo code:

exceptions.rb

module Exceptions
  class CriticalError < StandardError
    # Question: How do I attach a callback to this error? Whenever this error is raised, I also want it to ping_me() as a after callback
    def ping_me()
      ...
    end
  end
end

Desired outcome:

raise Exceptions::CriticalError # after a callback to this error being raised, it will run the ping_me() method

Question:

How do I do this in rails? I saw a rescue_from method but I think that is only available inside a controller

Thank you very much!


Solution

  • Ok, I figured this out

    module Exceptions
      class CriticalError < StandardError
        def initialize(error_message)
          ping_me()
          super(error_message)
        end
    
        def ping_me()
          ....
        end
      end
    end
    
    
    raise Exceptions::CriticalError.new("something went wrong!")