Created
December 26, 2012 15:53
-
-
Save bf4/4381029 to your computer and use it in GitHub Desktop.
Rails error handling for the view
This file contains 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
# sources: | |
# http://www.igodigital.com/blog/blog/notes-on-cyber-weekend-targeted-email-campaigns/custom-error-handling-in-rails-303 | |
# To test in dev, use the production setting below | |
# config/environments/development.rb | |
config.consider_all_requests_local = false | |
# delete the 404.html, and 500.html files. | |
# generate an error controller | |
`rails g controller Errors 404 500` | |
class ApplicationController < ActionController::Base | |
unless config.consider_all_requests_local | |
rescue_from Exception, :with => :render_error | |
rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found | |
rescue_from ActionController::RoutingError, :with => :render_not_found | |
rescue_from ActionController::UnknownController, :with => :render_not_found | |
# customize these as much as you want, ie, different for every error or all the same | |
rescue_from ActionController::UnknownAction, :with => :render_not_found | |
end | |
private | |
def render_not_found(exception) | |
render :template => "/errors/404.html.erb", :status => 404 | |
end | |
def render_error(exception) | |
# you can insert logic in here too to log errors | |
# or get more error info and use different templates | |
render :template => "/errors/500.html.erb", :status => 500 | |
end | |
end | |
# . In Rails 3, rescue_from ActionController::RoutingError is actually broken. | |
# It will be fixed in Rails 3.1, but until then, we have a little bit of a hack to work around this problem. | |
# let's just make a route that will catch all the ones | |
# that don't get found in our current routes.rb file. | |
# At the bottom of config/routes.rb, add this: | |
match '*a', :to => 'errors#404' | |
# The *a signifies params[:a] and will match any route requested. | |
# For other ways to render errors, look into render_optional_error_file | |
# If executing queries from views, you'll only get a general error instead of record not found |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment