Ruby on rails 从路由错误中营救rails 3.1

Ruby on rails 从路由错误中营救rails 3.1,ruby-on-rails,ruby,actioncontroller,Ruby On Rails,Ruby,Actioncontroller,如何在rails 3.1应用程序中避免路由错误。如果我没有弄错的话,可以在application controller中使用rescue\u from RoutingError,但现在不可能了。没有很好的方法来处理它,但有一些解决方法。讨论得出以下建议: 路线 将以下内容添加到路由文件: 匹配“*”,:to=>“主页#路由错误” 并处理此操作中的错误: def routing_error render text: "Not found, sorry", status: :not_found

如何在rails 3.1应用程序中避免路由错误。如果我没有弄错的话,可以在application controller中使用
rescue\u from RoutingError
,但现在不可能了。

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

路线

将以下内容添加到路由文件:

匹配“*”,:to=>“主页#路由错误”

并处理此操作中的错误:

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

我无法复制@matthew savage的结果。然而,根据另一个StackOverflow问题上的Rails指南,我这样解决了这个问题:

routes.rb

match "*gibberish", :to => "home#routing_error"
请注意,我是如何在通配符后包含文本的。控制器状态良好,如上图所示:

控制器/home_controller.rb

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

路由.rb

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

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

  • 轨道4:

    get'*unmatched_route'=>'应用程序#未找到提升_!'

应用程序\u控制器.rb

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

技术上更正确的响应应该是
呈现文本:“找不到,抱歉”,状态::找不到,内容类型:Mime::HTML
为了正确处理像
/icon.png
这样的响应,@aboutaaron的解决方案对我有效。只是路线模式中的一个“*”不起作用。需要添加一些废话:)