Last active
December 15, 2015 10:49
-
-
Save maxivak/5248696 to your computer and use it in GitHub Desktop.
Rails custom 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 | |
private | |
def render_error(status, exception) | |
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
# app/views/errors/error_404.html.haml | |
%h1 Page not found | |
%div | |
%b We are sorry | |
%p | |
The content that you requested could not be found. | |
%p | |
You tried to access '#{@not_found_path}', which is not a valid page. | |
%p | |
Want to | |
%a{href: root_path} go back to our home page | |
and try again? |
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 | |
@not_found_path = params[:not_found] | |
end | |
def error_500 | |
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
# config/routes.rb | |
# at the end of file | |
unless Rails.application.config.consider_all_requests_local | |
match '*not_found', to: 'errors#error_404' | |
end | |
# if you want to test pages in browser | |
get "errors/error_404" | |
get "errors/error_500" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment