Redirecting to a 500 page when an AJAX call fails in Ruby on Rails


I'm working with an application built in Ruby on Rails with very poor error handling right now. If a controller method is executed via ajax, and that method results in a 500 (or 404 or any other response) the 500.html page is rendered and returned as the result to the AJAX request. Obviously the javascript doesn't know what to do with that HTML and the web page looks like it's just waiting for a response.

Is there an easy way in rails to render an error.rjs template anytime an error occurs during an AJAX call?

Best Solution

You can use respond_to inside a controller's rescue_action or rescue_action_in_public method. Consider the following controller:

class DefaultController < ApplicationController

  def index
    raise "FAIL"

  def rescue_action(exception)
    respond_to do |format|
      format.html { render :text => "Rescued HTML" }
      format.js { render :action => "errors" }