1

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?

5
  • Don't rescue Exception, it's evil. Rescue StandardError if you have to. And BTW could you be a little bit more specific? What does it mean it 'didn't work'? Commented Dec 20, 2018 at 12:51
  • Thank you for this. Do you have any other way? I want when anyone type anything after the url that doesn't have in the route to bring 404 html page Commented Dec 20, 2018 at 13:12
  • Rails by default call 404.html from public folder, you can also define 404 to an custom controller by adding match '404', to: 'custom_errors#not_found', via: :all in routes.rb and config.exceptions_app = routes in application.rb Commented Dec 20, 2018 at 13:13
  • Can you put this in the answer section but with more explanation please Commented Dec 20, 2018 at 13:15
  • Here is a video for the solution youtube.com/watch?v=OWGCiHDP-u4&t=144s Commented Dec 21, 2018 at 21:35

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.