从路由错误中解救Rails 3.1

7

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

3个回答

7

没有一种很好的方式来处理它,但有一些变通方法。在这里讨论提出了以下建议:

路由

在您的路由文件中添加以下内容:

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 这样的响应。 - kizzx2
实际上,@aboutaaron的解决方案对我有用。只是在路由模式中加入一个“*”并不起作用。需要添加一些CRAP :) - Satya Kalluri

7

我无法复制@matthew-savage的结果。然而,根据Rails指南中有关路由全局匹配和另一个StackOverflow问题上的此问题,我解决了这个问题:

routes.rb

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

请注意,我在通配符后包含了文本。控制器按上述方式运行良好。

controller/home_controller.rb

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

0

好的 样例

route.rb

  • Rails 3:

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

  • Rails 4:

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

Rails 3:match '*unmatched_route', :to => 'application#raise_not_found!' Rails 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接