Render cool error pages in production with Rails 3.2
Since Rails 3 you cannot directly handle exceptions in the middleware layer, like RoutingError, in your controller (e.g. with the rescuefrom helper). Rails 3.2. lets you configure an exceptionsapp, which will be used in production mode to handle you're exceptions.
Use Routes Engine as exceptions_app
You can use the Routes Engine as exceptions_app with a simple setting in application.rb
class Application < Rails::Application ... config.exceptions_app = self.routes ... end
Now you can simply route your exceptions to your ExceptionController
MyApp::Application.routes.draw do ... match '/404', :to => "exceptions#render_404" ... end
Use custom Rack application as exceptions_app
You can use any Rack application as exceptionsapp. Since a Rails controller is basically a Rack application, you can also use your ExceptionController directly as exceptionsapp. Use a lambda expression, because the controller name constant is not yet available in the initialization stage.
class Application < Rails::Application ... config.exceptions_app = lambda do |env| ExceptionController.action(:render_error).call(env) end ... end
Get exception diagnostics in your controller
In your controller you can easily get the exception's properties (e.g. statuscode).
class ExceptionController < ActionController::Base layout 'application' def render_error @exception = env["action_dispatch.exception"] @status_code = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code render :error_page, status: @status_code, layout: true end end