How to properly render custom 404 and 500 pages? - ruby-on-rails

Is there are way to tell Rails to render your custom error pages (for example, the ones you write in your ErrorsController)? I've searched many topics, and the one that seems to kinda work was to add to your ApplicationController something like
if Rails.env.production?
rescue_from Exception, :with => :render_error
rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found
rescue_from ActionController::UnknownController, :with => :render_not_found
rescue_from ActionController::UnknownAction, :with => :render_not_found
end
and then you write your methods render_error and render_not_found the way you want. This seems to me like a really unelegant solution. Also, it's bad, because you have to know exactly what are all the errors that could happen. It's a temporary solution.
Also, there is really no easy way to rescue an ActionController::RoutingError that way. I saw that one way was to add something like
get "*not_found", :to => "errors#not_found"
to your routes.rb. But what if you want to raise somewhere an ActionController::RoutingError manually? For example, if a person who is not an administrator tries to go to "adminy" controllers by guessing the URL. In those situations I prefer raising a 404 more than raising an "unauthorized access" error of some kind, because that would actually tell the person that he guessed the URL. If you raise it manually, it will try to render a 500 page, and I want a 404.
So is there a way to tell Rails: "In all cases you would normally render a 404.html or a 500.html, render my custom 404 and 500 pages"? (Of course, I deleted the 404.html and 500.html pages from the public folder.)

Unfortunately there aren't any methods I know of that can be overridden to provide what you want. You could use an around filter. Your code would look something like this:
class ApplicationController < ActionController::Base
around_filter :catch_exceptions
protected
def catch_exceptions
yield
rescue => exception
if exception.is_a?(ActiveRecord::RecordNotFound)
render_page_not_found
else
render_error
end
end
end
You can handle each error as you see fit in that method. Then your #render_page_not_found and #render_error methods would have to be something like
render :template => 'errors/404'
You would then need to have a file at app/views/errors/404.html.[haml|erb]

Related

How to add 404 error page in ruby on rails app?

Can you help me in this. I want to add 404 error page to my website.
I tried many ways but nothing works for me.
Here is one of them.
ApplicationController
unless ActionController::Base.consider_all_requests_local
rescue_from Exception, :with => :render_404
end
private
def render_404
render :template => 'error_pages/404', :layout => false, :status => :not_found
end
Then set up error_pages/404.html
Can anyone fix this?
Rescuing 404 (usually originating from ActiveRecord::RecordNotFound) from your controller will not always help, because there're also routing errors (ActionController::RoutingError)
To present exceptions to user rails calls config.exceptions_app, which defaults to ActionDispatch::PublicExceptions.new(Rails.public_path) and just renders public/404.html etc.
For most cases it's enough to place your error pages there, but if you absolutely must render something dynamic - you can override the exceptions app.
One common hack is to route exceptions back into your main routes via config.exceptions_app = self.routes and adding regular routes to handle them:
get '/404', to: 'errors#not_found'
get '/422', to: 'errors#unacceptable'
get '/500', to: 'errors#server_error'
But beware, that if there's already an exception - you may get an exception loop, so it's better to have separate error handling app/engine
If you are simply wanting custom static error pages, you can change the HTML inside of public/404.html, public/422.html and public/500.html.

Get exception content in Rails Router

So I handle exceptions with an error controller to display dynamic content to my users in production. I have it in my route file to do:
# Errors
%w( 404 422 500 ).each do |code|
get code, :to => "errors#show", :code => code
end
The only problem is now that I'm routing on errors such as that I lose information in my controller when I want to notify Airbrake. How can I maintain the exception information and send it to Airbrake on a 500? Right now all I get is the env that was occurring at the time of the exception which is less helpful for debugging purposes.
class ErrorsController < ApplicationController
def show
notify_airbrake(env)
render status_code.to_s, :status => status_code
end
protected
def status_code
params[:code] || 500
end
end
Are you handling an error by redirecting to a URL like http://your.site/500? That will be just an HTTP request like any other, losing the exception context you're after. Instead, you probably want to be using ActionController's Rescue functionality. It would look like this:
class ApplicationController < ActionController::Base
rescue_from StandardError, with: :render_error
private
def render_error(error)
notify_airbrake(error)
render text: 500, status: 500
end
end
You can add multiple rescue_from declarations to handle different kinds of error, like the ActiveRecord::RecordNotFound from the Rails guide's example.

rails handling 404 on webrick getting ActiveRecord::RecordNotFound - simple questioon

So, I have a catch all route that is going to act like a vanity url piece. So, I have a call:
def show_profile
url=VanityUrl.find_by_url!(params[:username])
...
end
I'm seeing somewhat different info for how I should be handling the ActiveRecord::NotFound error. I just want it to return a template in shared/404.html.erb
How would I do this?
You can to use in the application controller
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
def record_not_found
# logger, flash[:error], render, redirect, etc if RAILS_ENV == "production"
end
As I understood, if record not found, we need to show /shared/404.html.erb.
def show_profile
url = VanityUrl.find_by_url!(params[:username]) rescue nil
unless url
render "#{RAILS_ROOT}/shared/404.html.erb"
return
end
end
Should work.
Reference: http://guides.rubyonrails.org/layouts_and_rendering.html

rails handle 404 with url redirect

I am looking to use rails to redirect links that I am sure are out there on the internet from an old domain of mine to a new one.
I would like to take address example.com/about ( about will not exist anymore)
and in my application_controller to take the 404, inspect the url and then redirect to
newexample.com/about
what's the best way to do this?
Add this to the end of your Routes file:
map.connect '*path', :controller => 'some_controller', :action => 'some_action'
This will catch any 404. Within the controller and action that will handle this route, use params[:path] to examine the url. Then you can redirect_to based on whatever is contained in params[:path].
You need to use rescue_from. In your ApplicationController, add something like:
rescue_from ActionController::RoutingError, :with => :redirect_missing
rescue_from ActionController::UnknownController, :with => :redirect_missing
rescue_from ActionController::UnknownAction, :with => :redirect_missing
def redirect_missing
redirect_to "http://newexample.com/about"
end

Rails: Custom behavior for specific HTTP error codes

I am working on a RoR website and would like to handle server errors (400, 404, 500, etc.) individually. Also, since the website is dynamic I would like to handle the errors within the rails environment rather than at the server level.
An example of what I would like to do could be to present the user with optional material or a search bar when she bumps into a page or template that will not load or simply does not exist.
So, I did a bit of reading and I think that using the rescue_from exception handler is the way to go in my case. (Would be more than happy to hear if any of you have a different opinion).
I have a simple working prototype (see code below) up and running, however, I get an error when I include the following exception handler to the code:
rescue_from ActionController::MissingTemplate, :with => :not_found #404
Now, I can't see that I have a spelling error and I have seen this line in code posted on the web. However, when I include it I get the following routing error:
Routing Error No route matches "/errorhandle" with {:method=>:get}
I am working on rails 2.3.5, perhaps that has got something to do with it?
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery #See ActionController::RequestForgeryProtection for details
#ActiveRecord exceptions
rescue_from ActiveRecord::RecordNotFound, :with => :not_found #400
#ActiveResource exceptions
rescue_from ActiveResource::ResourceNotFound, :with => :not_found #404
#ActionView exceptions
rescue_from ActionView::TemplateError, :with => :not_found #500
#ActionController exceptions
rescue_from ActionController::RoutingError, :with => :not_found #404
rescue_from ActionController::UnknownController, :with => :not_found #404
rescue_from ActionController::MethodNotAllowed, :with => :not_found #405
rescue_from ActionController::InvalidAuthenticityToken, :with => :not_found #405
rescue_from ActionController::UnknownAction, :with => :not_found #501
# This particular exception causes all the rest to fail.... why?
# rescue_from ActionController::MissingTemplate, :with => :not_found #404
protected
def not_found
render :text => "Error", :status => 404
end
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
end
Take a quick look at these:
http://www.ruby-forum.com/topic/47898
http://henrik.nyh.se/2008/09/404-invalid-rails-format
In particular, a post in the first link:
You can't use a regular 'rescue' keyword to rescue MissingTemplate
exception.
Use rescue_action instead, for example:
def rescue_action(exception)
if ::ActionController::MissingTemplate === exception
render :text => 'rescued'
else
super
end
end
Kent.

Resources