【发布时间】:2012-03-15 15:12:47
【问题描述】:
如何在 rails 3.1 应用程序中从 RoutingError 中解救出来。如果我没记错的话,可以在应用程序控制器中使用rescue_from RoutingError,但现在不可能了。
【问题讨论】:
标签: ruby-on-rails ruby actioncontroller
如何在 rails 3.1 应用程序中从 RoutingError 中解救出来。如果我没记错的话,可以在应用程序控制器中使用rescue_from RoutingError,但现在不可能了。
【问题讨论】:
标签: ruby-on-rails ruby actioncontroller
没有很好的方法来处理它,但有一些解决方法。讨论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等响应
我无法复制@matthew-savage 的结果。但是,根据关于另一个 StackOverflow 问题的 route globbing 和 this 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
【讨论】:
好的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
【讨论】: