Dynamic Error Pages Rails 3
Contents |
You may have noticed the 404.html, 422.html and 500.html files that are generated with every new Rails project and wondered if there's a rails error page clean way to style them like the rest of your application. There
Rails Exceptions_app
is, and it's surprisingly simple. Basic Implementation The default status code templates are served by a Rack exception application. rails render 404 page You can override this to be any Rack compatible app, including your applications router: # config/application.rb config.exceptions_app = self.routes This will route any exceptions caught to your router Rack app. rails error page gem Now you'll want to define routes to display those errors yourself: # config/routes.rb get "/404", :to => "errors#not_found" get "/422", :to => "errors#unacceptable" get "/500", :to => "errors#internal_error" This will route each error code to it's respective action in ErrorsController. Now we'll want to define those actions: class ErrorsController < ApplicationController def not_found render :status => 404 end def unacceptable render :status
Rails 4 Exceptions_app
=> 422 end def internal_error render :status => 500 end end We tell each action to render the appropriate HTTP status code related to the error that's been caught. All that's left to do now is create the view related to each action and you're done: # app/views/errors/not_found.html.haml %h1 404 - Not Found When we visit /404 our 404 - Not Found view should render as expected. Now you can style your error pages without having to duplicate any styles into the public directory of your application. Optimising Our Errors Controller So far we've got working error pages, but it doesn't feel like the most DRY implementation. We could make it more RESTful by refactoring our errors controller to use a show action instead. Let's start by changing our routes: # config/routes.rb %w( 404 422 500 ).each do |code| get code, :to => "errors#show", :code => code end Now we need to ensure our ErrorsController uses the code parameter we're passing through: class ErrorsController < ApplicationController def show render status_code.to_s, :status => status_code end protected def status_code params[:code] || 500 end end To
here for a quick overview of the site Help Center rails 404 route Detailed answers to any questions you might have Meta rails 404 page with layout Discuss the workings and policies of this site About Us Learn more about Stack Overflow
Rails 500 Error
the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x https://wearestac.com/blog/dynamic-error-pages-in-rails Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Dynamic error pages in Rails 3 up vote 37 down vote favorite 21 In Rails 2.3.x, you can http://stackoverflow.com/questions/5331008/dynamic-error-pages-in-rails-3 override render_optional_error_file like so: # ApplicationController.rb protected def render_optional_error_file(status_code) render :template => "errors/500", :status => 500, :layout => 'application' end However, Rails 3 no longer has render_optional_error_file. Instead, you need to override rescue_action_in_public, which you can do like so: # config/initializers/error_page.rb module ActionDispatch class ShowExceptions protected def rescue_action_in_public(exception) status = status_code(exception).to_s template = ActionView::Base.new(["#{Rails.root}/app/views"]) if ["404"].include?(status) file = "/errors/404.html.erb" else file = "/errors/500.html.erb" end body = template.render(:file => file) render(status, body) end end end This works, but does not use the application's layout. However, if you specify the layout path like so: body = template.render(:file => file, :layout => "layouts/application") # line 15 You get an Error during failsafe response: ActionView::Template::Error. Line 4 of application.html.erb:4 is: <%= stylesheet_link_tag "app", "jquery-ui", "jquery.fancybox", :cache => "all" %> Whatever ActionView normally uses to render templates isn't getting loaded. The stack trace is: /var/lib/gems/1.8/gems/actionpack-3.0.5/lib/action_view/helpers/asset_tag_helper.rb:794:in `join' /var/
Sign in Pricing Blog Support Search GitHub This repository Watch 2 Star 5 Fork 1 kwbock/dynamic_errors Code Issues 0 Pull requests 0 Projects 0 Pulse Graphs Dynamic error pages in Rails 25 commits 1 branch 4 releases Fetching contributors https://github.com/kwbock/dynamic_errors MIT Ruby 100.0% Ruby Clone or download Clone with HTTPS Use Git or checkout with http://railscasts.com/episodes/53-handling-exceptions-revised?view=comments SVN using the web URL. Open in Desktop Download ZIP Find file Branch: master Switch branches/tags Branches Tags master Nothing to show v0.2.0 v0.1.2 v0.1.1 help Nothing to show New pull request Fetching latest commit… Cannot retrieve the latest commit at this time. Permalink Failed to load latest commit information. app/views/errors lib test .gitignore Gemfile Gemfile.lock LICENSE.txt README.rdoc Rakefile error page VERSION dynamic_errors.gemspec README.rdoc dynamic_errors Currently this gem is fairly broken. We are working on updating it to work with the latest minor version of Rails (at the time of this post, 3.2.x). Thank you for your patience. This gem wraps the standard Rails 3 error pages (public/(404|422|500).html) with the applications layout. Any further changes to the application layout will be reflected on the error pages, preventing having to make layout changes in three places. Installation rails error page gem install dynamic_errors Usage add “require 'dynamic_errors'” to environment.rb Create the following views if you wish to override the standard error message errors/404.html.erb errors/422.html.erb errors/500.html.erb Compatibility Currently the gem has only been tested (very briefly at that) with Rails -v3.0.3-7. Rails 2.x may be added if requested. Contributing to dynamic_errors Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it Fork the project Start a feature/bugfix branch Commit and push until you are happy with your contribution Make sure to add tests for it. This is important so I don't break it in a future version unintentionally. Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it. Copyright Copyright © 2011 Kyle Bock. See LICENSE.txt for further details. Contact GitHub API Training Shop Blog About © 2016 GitHub, Inc. Terms Privacy Security Status Help You can't perform that action at this time. You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Handling Exceptions (revised) Apr 20, 2013 | 11 minutes | Controllers, Routing, Production, Rack By default, Rails will render a static error file when an exception occurs in production. Here you will learn how to fully customize this behavior and render dynamic error pages. Subscribe to Watch Episode Tweet Show NotesASCIIcast36 CommentsSimilar EpisodesNext Episode >< Previous Episode lazylester over 3 years ago In order to test the dynamic generation of error pages, you need to be in production environment, which is incompatible with running your entire test suite, normally in test environment. Similarly hacking the config.consider_all_requests_local parameter may is not viable except as a short-term hack to see dynamic error pages operating in dev or test environment. So I found it best to move the ErrorsController and associated views into a Rails engine... that way it can have a test suite of its own, running the tests in production environment. Bharat Ruparel over 3 years ago @laylester, could you please put out a sample/example on Github? Thanks. Bharat lazylester over 3 years ago @Bharat Ruparal https://github.com/lazylester/error_pages_engine Greg Silcox over 3 years ago This is certainly an area of my apps that needs some TLC. Thanks! Flambino over 3 years ago Nice episode, but it would be beneficial to add something like response.status = request.path[1..-1] to make the status code carry over (if anyone knows of a nicer way to do this, speak up). Otherwise, the error pages will all have a status of 200 OK since the error controller itself responded normally. Kamil Politowicz over 3 years ago Indeed - it may be not needed for HTML version, but definitely JSON API would benefit from having the right status code: render json: {error: @exception.message}, status: request.path[1..-1] Flambino over 3 years ago Yeah, web APIs are (or should be) sticklers for proper status codes, but any ol' HTML browser can infer a lot from the status code too. Whether or not to use the URL when auto-completing an address for the user, for instance. It's annoying to have the browser remember a URL for an error page, only because that page accidentally sent a 200 OK Tobias about 3 years ago I found a replacement for request.path[1..-1] posted by Jeroen Rosenberg: ruby status_code = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code Jonathan Berglund over 3 years ago Has anyone found