Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails rescue_from stops execution flow

I'm having problems using the rescue_from

class SimpleError < StandardError; end

before_action :raise_exception
rescue_from SimpleError, with: :rescue_exception    

def raise_exception
    raise SimpleError
end

def rescue_exception
    log $!
end

def index
    @unreachable_code = true
def

In this code as you can see I simply raise an exception before the action starts, that is caught by the rescue_exception method. The problem is that after I catch the exception the application flow stops and the action code is never reached. Is it possible to continue the execution after the exception is rescued?

like image 930
bukk530 Avatar asked Mar 17 '23 20:03

bukk530


1 Answers

Short answer, no. rescue_from is intended to handle exceptions that are otherwise uncaught.

If you want to catch a particular exception for every action in a controller, I would recommend an around_action.

class MyController < ApplicationController
  class SimpleError < StandardError; end

  around_action :handle_simple_errors

  def index
    # code that might raise SimpleError
    @unreachable_code = true
  def

  private

  def handle_simple_errors
    begin
      yield
    rescue SimpleError
      # handle SimpleError however
    end
  end
end
like image 184
messanjah Avatar answered Mar 29 '23 12:03

messanjah