Created
August 15, 2013 19:16
-
-
Save kitwalker12/6243865 to your computer and use it in GitHub Desktop.
Custom 404 & 500 Error Pages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
#... | |
unless Rails.application.config.consider_all_requests_local | |
rescue_from Exception, with: lambda { |exception| render_error 500, exception } | |
rescue_from ActionController::RoutingError, ActionController::UnknownController, ::AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, with: lambda { |exception| render_error 404, exception } | |
end | |
#... | |
protected | |
#... | |
def not_found | |
raise ActionController::RoutingError.new('Not Found') | |
end | |
def restrict_to_development | |
head(:bad_request) unless Rails.env.development? | |
end | |
#... | |
private | |
def render_error(status, exception) | |
if(status == 404) | |
logger.info "Not Found: '#{request.fullpath}'.\n#{exception.class} error was raised for path .\n#{exception.message}" | |
else | |
logger.info "System Error: Tried to access '#{request.fullpath}'.\n#{exception.class} error was raised for path .\n#{exception.message}" | |
end | |
respond_to do |format| | |
format.html { render template: "errors/error_#{status}", layout: 'layouts/application', status: status } | |
format.all { render nothing: true, status: status } | |
end | |
end | |
#... | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ErrorsController < ApplicationController | |
def error_404 | |
render status: 404 | |
end | |
def error_500 | |
render status: 500 | |
end | |
def not_found | |
raise ActionController::RoutingError.new('Not Found') | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MyApp::Application.routes.draw do | |
#... | |
#Custom Error Generating controller | |
get "/errors/not_found" => 'errors#not_found' | |
get "/errors/server_error" => 'errors#server_error' | |
unless Rails.application.config.consider_all_requests_local | |
match '*not_found', to: 'errors#error_404' | |
end | |
#... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment