Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render the same 404 page for all unknown requests, including images, in Rails 3.2 without specifying each file format individually?

We use the following catch-all route in routes.rb for 404s:

# Catches all 404 errors and redirects
match '*url' => 'default#error_404'

But this generates a 500 internal server error below because we don't specifically catch PNG formats in error_404.

Started GET "/images/doesnotexistyo.png" for 71.198.44.101 at 2013-03-08 07:59:24 +0300
Processing by DefaultController#error_404 as PNG
  Parameters: {"url"=>"images/doesnotexistyo"}
Completed 500 Internal Server Error in 1ms

ActionView::MissingTemplate (Missing template default/error_404, application/error_404 with {:locale=>[:en], :formats=>[:png], :handlers=>[:erb, :builder]}. Searched in:
  * "/home/prod/Prod/app/views"

Ideally, all unknown requests would render the default#error_404 HTML action. We can't figure out how to get format.any to render the 404 HTML action. How can all unknown requests get rendered with the error 404 HTML response?

like image 682
Crashalot Avatar asked Oct 15 '25 15:10

Crashalot


1 Answers

in Application Controller: Use rescue_from

rescue_from "ActionController::UnknownAction", :with => :render_404
rescue_from "ActionController::RoutingError",  :with => :render_404

def render_404
  respond_to do |format|
    format.html { render :template => "<PATH_OF_404_ERROR_TEMPLATE>", :status => 404 }       
    format.xml { head 404 }
    format.js { head 404 }
    format.json { head 404 }
  end
  return false
end
like image 167
shweta Avatar answered Oct 18 '25 05:10

shweta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!