Tuesday, 9 October 2018

404 page

Please visit site:

https://mattbrictson.com/dynamic-rails-error-pages

rails generate controller errors not_found internal_server_error
This creates app/controllers/errors_controller.rb with corresponding view templates in app/views/errors/ for the not found (404) and internal server error (500) pages. (Ruby methods declared with def can’t start with numbers, so use the spelled-out error names instead.)

2SEND THE RIGHT STATUS CODES

class ErrorsController < ApplicationController
  def not_found
    render(:status => 404)
  end

  def internal_server_error
    render(:status => 500)
  end
end
Normally Rails sends an HTTP status of 200 OK when it renders a view template, but in this case we want 404 or 500 to be sent according to error page being rendered. This requires a slight tweak to the errors_controller.rb that Rails generates. You don’t need to specify the name of the template to render, because by convention it is the same as the action name.

3CONFIGURE THE ROUTES

match "/404", :to => "errors#not_found", :via => :all
match "/500", :to => "errors#internal_server_error", :via => :all
Rails expects the error pages to be served from /<error code>. Adding these simple routes in config/routes.rb connects those requests to the appropriate actions of the errors controller. Using match ... :via => :all allows the error pages to be displayed for any type of request (GET, POST, PUT, etc.).

4TELL RAILS TO USE OUR ROUTES FOR ERROR HANDLING

config.exceptions_app = self.routes
Add this line to config/application.rb. This tells Rails to serve error pages from the Rails app itself (i.e. the routes we just set up), rather than using static error pages in public/.

5. config/environments/development.rb:
config.consider_all_requests_local = false
























No comments:

Post a Comment