Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rescue_from for javascript requests

In my Rails 2.3.8 application I had a rescue_from code for exceptions, which are thrown during javascript actions:

rescue_from ::Exception, :with => :show_js_errors

...

def show_js_errors exception
  if request.format == :js
    flash[:error] = 'some error occured'
    render :update do |page|
      page.redirect_to({:controller => '/home', :action => :index})
    end
  else
    # use default error handling for non-JS requests
    rescue_action_without_handler(exception)
  end
end

So my users get an error message, if an ajax call runs into an error. In Rails 3, I can't simply call the default error handling, because the "without_handler" method doesn't exist any more.

update doh

I posted this after 3 hours of searching, but only 30 minutes after posting I found a solution myself.

Just re-raise the exception.

Since you are in the error handling, no further handling is done with this exception.

like image 701
neogrande Avatar asked Jul 25 '11 08:07

neogrande


1 Answers

Just reraise the exception.

def show_js_errors exception
  if request.format == :js
    flash[:error] = 'some error occured'
    render :update do |page|
      page.redirect_to({:controller => '/home', :action => :index})
    end
  else
    raise # <<
  end
end

http://simonecarletti.com/blog/2009/11/re-raise-a-ruby-exception-in-a-rails-rescue_from-statement/ concurs:

rescue_from ActiveRecord::StatementInvalid do |exception|
  if exception.message =~ /invalid byte sequence for encoding/
    rescue_invalid_encoding(exception)
  else
    raise
  end
end

[...]The exception is correctly rethrown but it isn't catched [sic] by the standard Rails rescue mechanism and the standard exception page is not rendered.

like image 140
michaelb958--GoFundMonica Avatar answered Oct 16 '22 16:10

michaelb958--GoFundMonica