Rescue_from for javascript requests
Asked Answered
N

1

20

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.

Neral answered 25/7, 2011 at 8:57 Comment(5)
Thanks for posting your solution.Ketch
Tks dude! you helped me :PSewellel
Localised to there being no question if an answer is half of itDaunt
Can you please add this as an answer?Eggleston
You should mark the question as answered.Clearsighted
M
1

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.

Mariahmariam answered 10/2, 2014 at 22:12 Comment(1)
Meta-commentary: I'm posting this because, well, nobody else has.Mariahmariam

© 2022 - 2024 — McMap. All rights reserved.