11

In Rails 5, when a callback needs to cancel later callbacks, the recommended process is documented as "you should explicitly throw :abort."

My question is: how is it recommended that this exception be caught?

My current solution is to catch UncaughtThrowError in my ApplicationController - given the way it's documented, I thought this feature would trigger some magic in Rails or a Rack middleware to immediately move to the rendering (ActionView) phase.

sameers
  • 4,855
  • 3
  • 35
  • 44

2 Answers2

1

Here are some examples of how to use the throw/catch in ruby.

For Rails, I think something like this will do the trick:

class SomeController 
  def some_method 
    if catch(:abort) { mode.save }
      # success
    else
      # failure 
    end
  end
end
ekampp
  • 1,904
  • 18
  • 31
  • 1
    I don't know who gave you the upvote but I seriously doubt this will work for a variety of reasons. Did you test this at all? – Joshua Pinter Jul 21 '21 at 15:43
1

You would probably have to write a method that overrides the underlying method for processing callbacks to have a catch :abort {} that handles it, which feels like too much magic.

I think using a rescue_from UncaughtThrowError in the controller you're throwing in seems a better approach vs. having it in the ApplicationController unless this is really common callback, in which case you probably want a Concern?

I went down this road for a day, and then decided to not use a callback for what I wanted to do, which eliminated the whole need for the callbacks, throws, rescues, and catches.

Still, I'm sure there are good cases for this approach, but it's not well documented as to how.

tamouse
  • 2,169
  • 1
  • 19
  • 26