重定向 404、422、500 Ruby 在 rails

Redirect 404, 422, 500 Ruby On rails

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

我试过了,但它对 404 错误有效。

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

谢谢!

在你的路由文件中:

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

在您的应用程序控制器中

#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

对于生产环境:

在 production.rb 文件中,添加:

config.exceptions_app = routes

在routes.rb文件中,添加: 添加

%w[404 422 500 503].each do |code| get code, to: 'exceptions#show', code: code end

创建exceptions_controller.rb文件,添加:

class ExceptionsController < ApplicationController
  # GET /exceptions/:code
  def show
    status_code = params[:code] || 500
    render status_code.to_s, status: status_code
  end
end

在目录中创建,404.html.erb,422.html.erb,500.html.erb,503.html.erb:views/exceptions

尽情享受吧!