【问题标题】:Redirect 404, 422, 500 Ruby On rails重定向 404、422、500 Ruby On rails
【发布时间】:2016-01-19 23:44:26
【问题描述】:

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

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

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

    在您的路线文件中:

    #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

    【讨论】:

    • 是的,但我想重定向到 root_url
    • 只需将render file 更改为redirect_to
    【解决方案2】:

    对于生产环境:

    在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

    享受吧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多