How to use rails rescue_from outside the controller

1.4k Views Asked by At
  • I am using GrapeApi and I am using service design pattern so I need to handle exceptions outside the controller, but rescue_from is only working inside controllers. - I am using rescue ExceptionName in almost every method and I found that I am not respecting the DRY rule. so I created a file services/exception_handler_service.rb. and tried include ActiveSupport::Rescuable and it's just being ignored and extend ActiveSupport::Rescuable and throwing undefined method rescue_from.

is there a way I can use rescue_from outside the controller?

1

There are 1 best solutions below

0
mechnicov On

Here example for you in plain Ruby as idea using rescue_with_handler

require 'active_support/rescuable'


class MyError < StandardError
end

class MyClass
  include ActiveSupport::Rescuable

  rescue_from MyError, with: :catch_error

  def method_with_error
    raise MyError
    puts "I am after error"
  rescue MyError => e
    rescue_with_handler(e)
  end

  private

  def catch_error
    puts "Catch error"
  end
end

MyClass.new.method_with_error # will print Catch error