开发者

Show a 404 instead of 500 in Rails

开发者 https://www.devze.com 2022-12-25 11:36 出处:网络
In my rails app I have defined the routes so users can access records like http://mydomain.com/qwe2 But if they type a wrong \"qwe2\" they 开发者_如何学JAVAget a 500 page. I think a 404 would be more

In my rails app I have defined the routes so users can access records like http://mydomain.com/qwe2

But if they type a wrong "qwe2" they 开发者_如何学JAVAget a 500 page. I think a 404 would be more appropriate.

How can I change the error page that is shown? Thanks


Create a catch-all route at the bottom of config/routes.rb:

map.connect '*path', :controller => 'unknown_route'

Then in app/controllers/unknown_route_controller you can do:

class UnknownRouteController < ApplicationController
  def index    
    render :file => "#{Rails.root}/public/404.html", :layout => false,
           :status => 404
  end
end

This will render your 404 page for any unknown routes.


The only reason you get a 500 code is if your application throws an exception. This could be due to a missing route, where you do not have anything defined that matches that, or because your controller or view has crashed out.

In a production environment you might want to catch all errors generated by your application and present a better error screen, if appropriate, or a 'Not Found' page if required.

For example, a brute-force catch-all exception catcher might be defined as:

class ApplicationController < ActionController::Base
  if (Rails.env.production?)
    rescue_from Object, :with => :uncaught_exception_rescue
  end

protected
  def uncaught_exception_rescue(exception)
    render(:partial => 'errors/not_found', :status => :not_found)
  end
end

Returning a 404-type error is easy if you can tell when you want to do it:

render(:partial => 'errors/not_found', :status => :not_found)

Make sure you have some kind of default route or you will get these errors all the time. Usually this is done by adding a catch-all route at the very end of your routes.rb:

map.default '/*path', :controller => 'default', :action => 'show'

Then you can do whatever you want with this request.

0

精彩评论

暂无评论...
验证码 换一张
取 消