What people tend to do is to handle exception in controller with rescue_from, well it is totally fine. However there is also a different way by delegating the handling to router.
Configure the app to handle exception with Router
# config/application.rb
config.exceptions_app = self.routes
Tell Router how to handle error by matching status code
# config/routes.rb
Rails.application.routes.draw do
constraints Router::Error do
match '404' => 'errors#not_found', :via => :all
match '406' => 'errors#not_acceptable', :via => :all
match '410' => 'errors#gone', :via => :all
match '500' => 'errors#internal_server_error', :via => :all
end
end
Your are free to do whatever with your ErrorsController
# app/controllers/errors_controller.rb
class ErrorsController < ActionController::Base
def not_acceptable
respond_to do |format|
format.any { render :nothing => true, :status => 406 }
end
end
def not_found
respond_to do |format|
format.any(:json, :xml, :atom) { render :text => "Error: Page Not Found", :status => 404 }
end
end
def gone
respond_to do |format|
format.any(:json, :xml, :atom) {
render :text => "The page is gone", :status => 410
}
end
end
def internal_server_error
# do whatever you like - you get the idea
end
end