3

Suppose I have the following logic in my ApplicationController:

rescue_from ActionController::RoutingError, :with => :handle_routing_error

def handle_routing_error(exception)
 logger.info { "handling routing error: #{exception.message}" }
 render template: 'errors/error_404', status: 404
end

This renders my custom (and dynamic) 404 error page for all requests in the HTML format.

However, when someone provides a URL indicating a non-HTML format, e.g. mysite.com/missingfile.png this throws a 500 error becauses I don't have a error_404.png template:

Missing template errors/error_404, public_site/error_404, application/error_404 with {:locale=>[:en], :formats=>[:png], :handlers=>[:erb, :builder, :coffee, :rabl, :haml]}. Searched in:

How can I override the request format and always show my dynamic HTML 404 page? I want it to work like twitter: https://twitter.com/missingfile.png.

A key point is that this is a dynamic 404 page, so the usual public/404.html route does not work for me.

Thanks!

5
  • Also just a heads up: I do not want to render: none with status 404 for non-HTML formats, nor do I want to return a 406 error, which are both options on some blogs I have seen that deal with this topic. Commented Feb 19, 2013 at 6:11
  • What is your Rails version? I doubt you can still catch RoutingError from rescue_from as RoutingError is in middleware since 3.2.x and can't be caught at ApplicationController Commented Feb 19, 2013 at 8:12
  • Billy thanks, good point. I am using Rails 3.2.12. This rescue clause is only being used when I manually throw 404 exceptions from controllers. I just remembered that I have a catch all mapping: match '*not_found', to: 'errors#error_404. Commented Feb 19, 2013 at 17:30
  • Anyways, I got the behavior that I want working. I will update my question with the solution when I have a chance. Commented Feb 19, 2013 at 17:31
  • Yes, the error can be caught at specific controller level but not ApplicationController. Here is a good ref: coderwall.com/p/w3ghqq Commented Feb 19, 2013 at 17:39

1 Answer 1

1

Do this ...

#config/routes
get "*unmatched_route", :to => "application#error_page"


#controllers/application_controller
def error_page
  render :template => 'errors/error_404', status: 404
end
Sign up to request clarification or add additional context in comments.

1 Comment

it is reporting every page a 404

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.