如何显示404错误页面而不是路由错误?

时间:2022-10-07 00:28:38

In my Ruby on Rails application I want to show 404 error page instead of routing error when the given route does not matches or exists in my application. Can anybody help me to make it possible?

在我的Ruby on Rails应用程序中,当给定路由与我的应用程序中不匹配或存在时,我想显示404错误页面而不是路由错误。任何人都可以帮助我实现这一目标吗?

4 个解决方案

#1


13  

This is already the default behavior in production. In development environment routing errors are displayed to let the developer notice them and fix them.

这已经是生产中的默认行为。在开发环境中,会显示路由错误,以便开发人员注意并修复它们。

If you want to try it, start the server in production mode and check it.

如果要尝试,请在生产模式下启动服务器并进行检查。

$ script/rails s -e production

#2


7  

in ApplicationController

 rescue_from ActiveRecord::RecordNotFound, :with => :rescue404
 rescue_from ActionController::RoutingError, :with => :rescue404

  def rescue404
    #your custom method for errors, you can render anything you want there
  end

#3


6  

If you cannot easily run production mode locally, set the consider_all_requests_local to false in your config/environments/development.rb file.

如果您无法在本地轻松运行生产模式,请在config / environments / development.rb文件中将Conside_all_requests_local设置为false。

#4


0  

You could catch exception that is thrown when a route is not found and then render a custom page. Let me know if you need help with the code. There might be many other ways to do this but this definitely works.

您可以捕获未找到路由时引发的异常,然后呈现自定义页面。如果您需要有关代码的帮助,请与我们联系。可能还有很多其他方法可以做到这一点,但这肯定有效。

#1


13  

This is already the default behavior in production. In development environment routing errors are displayed to let the developer notice them and fix them.

这已经是生产中的默认行为。在开发环境中,会显示路由错误,以便开发人员注意并修复它们。

If you want to try it, start the server in production mode and check it.

如果要尝试,请在生产模式下启动服务器并进行检查。

$ script/rails s -e production

#2


7  

in ApplicationController

 rescue_from ActiveRecord::RecordNotFound, :with => :rescue404
 rescue_from ActionController::RoutingError, :with => :rescue404

  def rescue404
    #your custom method for errors, you can render anything you want there
  end

#3


6  

If you cannot easily run production mode locally, set the consider_all_requests_local to false in your config/environments/development.rb file.

如果您无法在本地轻松运行生产模式,请在config / environments / development.rb文件中将Conside_all_requests_local设置为false。

#4


0  

You could catch exception that is thrown when a route is not found and then render a custom page. Let me know if you need help with the code. There might be many other ways to do this but this definitely works.

您可以捕获未找到路由时引发的异常,然后呈现自定义页面。如果您需要有关代码的帮助,请与我们联系。可能还有很多其他方法可以做到这一点,但这肯定有效。