ruby-on-rails - 重定向 404、422、500 Ruby On rails

标签 ruby-on-rails ruby redirect http-status-code-404

我会被重定向到主页,只有 500、404、422 错误出现,是否可以“捕获”所有错误并重定向到主页?

我试过了,但它适用于 404 错误。

  match "*path" => redirect("/"), via: :get

谢谢!

最佳答案

在你的路由文件中:

#routes.rb
get '*unmatched_route', to: 'application#raise_not_found'

在你的应用程序 Controller 中

#application_controller.rb
rescue_from ActiveRecord::RecordNotFound, with: :not_found 
rescue_from Exception, with: :not_found
rescue_from ActionController::RoutingError, with: :not_found

def raise_not_found
  raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}")
end

def not_found
  respond_to do |format|
    format.html { render file: "#{Rails.root}/public/404", layout: false, status: :not_found }
    format.xml { head :not_found }
    format.any { head :not_found }
  end
end

def error
  respond_to do |format|
    format.html { render file: "#{Rails.root}/public/500", layout: false, status: :error }
    format.xml { head :not_found }
    format.any { head :not_found }
  end
end

您可以找到完整的资源 here

关于ruby-on-rails - 重定向 404、422、500 Ruby On rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34889043/

相关文章:

ruby-on-rails - 当 Rails 和 Sinatra 之间通过 memcached 共享数据时,如何修复 Sinatra 不处理 ActiveSupport

ruby-on-rails - Actioncable Nginx 和 Puma WebSocket 握手 : Unexpected response

ruby-on-rails - 带有自定义标识符(不是 id)的 Rails URL

ruby - Ruby 的 OptionParser 是如何工作的?

java - Android:延迟后重定向到另一个 Activity

java - JBoss 5.1.0.GA - 重定向到端口 443 不起作用,始终重定向到 8443

linux - 如何使 Wildfly 10.1.0 在 Linux Ubuntu 16.04 中使用 h2 (HTTP/2) 协议(protocol)在端口 80 和 443 (SSL) 上工作

ruby-on-rails - blueprint/screen.css 未预编译

ruby-on-rails - 将 validates_exclusion_of 坏词连接到一个单独的文件?

ruby - 如何在 Rails 4.1 中只在路由上写入一次 path_names 并使其可用于所有路由?