Use rescue_from on model concern

943 Views Asked by At

I want to use rescue_from method on a model concern but neither exception error is rescued to the method i specified:

require "active_support/concern"

module CustomErrorHandler
    extend ActiveSupport::Concern
    include ActiveSupport::Rescuable
    
    included do
        rescue_from StandardError, with: :capture_error
    end
    
    
    private
    
    def capture_error(e)
        puts "Error catched!"
    end
end

class FooClass
    include CustomErrorHandler
    
    def some_action
        raise StandardError, 'Error'
    end
end

err = FooClass.new
err.some_action

Traceback (most recent call last):
        2: from (irb):28
        1: from (irb):23:in `some_action'
StandardError (Error) # Didn't catch the error!

Anyone can help me on how can i solve this? Thanks!

1

There are 1 best solutions below

1
max On

This idea is fundamentially broken.

rescue_from is basically just syntactic sugar for:

class ThingsController < ApplicationController
  around_action :wrap_in_a_rescue

  def show
    raise SomeKindOfException
  end

  private

  def wrap_in_a_rescue
    begin
      yield
    rescue SomeKindOfException
      do_something_else
    end
  end

  def do_something_else
    render plain: 'Oh Noes!'
  end
end

It only works because the controller declares a callback.

Its use makes sense in a controller as it rescues exceptions that occur in its callbacks as well as in the method itself and can be used with inheritiance to customize the error responses. It use does not make very much sense outside of that context.

While you could maybe fix this code by including ActiveSupport::Callbacks and declaring the requisite callbacks it is most likely a very overcomplicated solution to the original problem which can most likely be handled with a simple rescue or composition.