Automatically handle unexpected Ajax errors in Rails

I’m busy working on a project that uses a lot of Ajax to deal with updates and lookups etc. Occasionally I write rubbish code and one of these methods break.

When using normal HTML this is not a problem because Rails presents the user with a nice message saying “We’re sorry but something went wrong…”.
But, with Ajax, Rails returns the exact same page which is useless in an Ajax call. Because of this, users are generally left without knowing if their request is taking a long time or has failed.

I dug into Rails error handling and decided to deal with this so that errors pop-up an alert message with the same message as the HTML 500 error. I also wanted to get more error information if I get an error in development.
The two magic methods you need to override in your application controller are: rescue_action_in_public and rescue_action_locally.

I simply defined my own version of these methods and checked for an Ajax call with a respond_to block. If the request is for standard HTML, I delegate the call back to the superclass so everything continues as normal and if it’s a Javascript call, I send back an alert message.

class ApplicationController < ActionController::Base

...

private
  def rescue_action_in_public(exception)
    respond_to do |want|
      want.html {
        super(exception)
      }
      want.js {
        render :update do |page|
          page.alert "We're sorry, but something went wrong.\nWe've been notified about this issue and we'll take a look at it shortly.\n\nPlease check that any update you tried has not been successful before trying it again."
        end
      }
    end
  end

  def rescue_action_locally(exception)
    respond_to do |want|
      want.html {
        super(exception)
      }
      want.js {
        render :update do |page|
          page.alert "Oops! I made a mistake\n#{exception.class}: #{exception.message}\nCheck the logs for more detail."
        end
      }
    end
  end

...

end

Comments (2)

Armand du PlessisDecember 30th, 2008 at 16:37

Nice, very useful thanks!

AmitJanuary 5th, 2009 at 05:02

good solution !!