重定向404,422,500 Ruby On rails

时间:2016-01-19 23:44:26

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

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

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

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

谢谢!

2 个答案:

答案 0 :(得分:3)

在你的路线档案中:

#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

答案 1 :(得分:1)

对于生产环境:

在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

在目录views/exceptions

中创建404.html.erb,422.html.erb,500.html.erb,503.html.erb

享受!