Reputation: 1829
In many cases people want to have separate error pages but in my case I want an custom error page on my homepage.
I found the link http://makandracards.com/makandra/12807-custom-error-pages-in-rails-3-2 this helps to make separate error pages.
Upvotes: 0
Views: 114
Reputation: 76774
I've worked extensively on this, and have created a gem called exceptions_handler
to make it easier for people to use
You can see a good tutorial here:
I've also written an exhaustive answer here
--
exceptions_app
The bottom line with your own error pages is to capture the error using the exceptions_app
middleware hook in Rails:
config.exceptions_app
sets the exceptions application invoked by theShowExceptionmiddleware
when an exception happens. Defaults toActionDispatch::PublicExceptions.new(Rails.public_path)
.
As the first answer has posted, you should apply this to your config/application.rb
, but I would disagree with sending the request to the routes file directly
--
Controller
A better way is to send the request to a controller action (we use exceptions#show
):
#config/application.rb
config.exceptions_app = ->(env) { ExceptionController.action(:show).call(env) }
#app/controllers/exception_controller.rb
class ExceptionController < ActionController::Base
#Response
respond_to :html, :xml, :json
#Dependencies
before_action :status
def show
render "index"
end
private
def status
@exception = env['action_dispatch.exception']
@status = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
@response = ActionDispatch::ExceptionWrapper.rescue_responses[@exception.class.name]
end
end
--
Views
This will allow you to create the following views:
#app/views/application/index.html.erb
<% render partial: "errors" if @status.present? %>
Upvotes: 2
Reputation: 1829
So I've made the following to help this:
Routes.rb:
match '/404', :to => 'home#not_found'
match '/422', :to => 'home#rejected'
match '/500', :to => 'home#server_error'
Application.rb
config.exceptions_app = self.routes
Home_controller.rb
def not_found
@errors = I18n.t("home.errors.error_404")
render 'index'
end
def rejected
@errors = I18n.t("home.errors.error_422")
render 'index'
end
def server_error
@errors = I18n.t("home.errors.error_500")
render 'index'
end
On my home/index page:
<%= render :partial => 'errors', :errors => @errors %>
And a simple partial _errors:
<div class="row">
<% if @errors %>
<div class="alert alert-wide alert-info">
<p style="display:inline"><%= @errors %></p>
</div>
<% end %>
</div>
Upvotes: 0