【问题标题】:Rescue from routing error rails 3.1从路由错误轨道 3.1 中拯救
【发布时间】:2012-03-15 15:12:47
【问题描述】:

如何在 rails 3.1 应用程序中从 RoutingError 中解救出来。如果我没记错的话,可以在应用程序控制器中使用rescue_from RoutingError,但现在不可能了。

【问题讨论】:

    标签: ruby-on-rails ruby actioncontroller


    【解决方案1】:

    没有很好的方法来处理它,但有一些解决方法。讨论here 产生以下建议:

    路线

    将以下内容添加到您的路线文件中:

    match "*", :to => "home#routing_error"

    并处理此操作中的错误:

    def routing_error
      render text: "Not found, sorry", status: :not_found
    end
    

    【讨论】:

    • 技术上更正确的响应是render text: "Not found, sorry", status: :not_found, content_type: Mime::HTML,以正确处理/icon.png等响应
    • 事实上,@aboutaaron 的解决方案对我有用。仅路由模式中的“*”不起作用。需要添加一些垃圾:)
    【解决方案2】:

    我无法复制@matthew-savage 的结果。但是,根据关于另一个 StackOverflow 问题的 route globbingthis question 的 Rails 指南,我这样解决了这个问题:

    routes.rb

    match "*gibberish", :to => "home#routing_error"
    

    请注意我是如何在通配符之后包含文本的。控制器没问题如上图:

    控制器/home_controller.rb

    ....
    def routing_error
        render text: "Not found, sorry", status: :not_found
    end
    

    【讨论】:

      【解决方案3】:

      好的example

      route.rb

      • 轨道 3:

        match '*unmatched_route', :to => 'application#raise_not_found!'

      • 导轨 4:

        get '*unmatched_route' => 'application#raise_not_found!'

      application_controller.rb

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-22
        • 2016-06-21
        • 2013-11-27
        • 2015-06-13
        • 1970-01-01
        相关资源
        最近更新 更多