Show a 404 instead of 500 in Rails

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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 get a 500 page. I think a 404 would be more appropriate.

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

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!