Skip to content

Instantly share code, notes, and snippets.

@runlevel5
Last active October 20, 2019 08:56
Show Gist options
  • Select an option

  • Save runlevel5/f2b4565949f7c988c9481b3c5dc15dba to your computer and use it in GitHub Desktop.

Select an option

Save runlevel5/f2b4565949f7c988c9481b3c5dc15dba to your computer and use it in GitHub Desktop.
Rails way to let router to handle all exception

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment