如何从RoutingError
Rails 3.1 应用程序中救援。如果我没记错的话,可以rescue_from RoutingError
在应用程序控制器中使用,但现在不可能。
3 回答
There is no great way to handle it, but there are a few workarounds. The discussion here yields the following suggestion:
Routes
Add the following to your routes file:
match "*", :to => "home#routing_error"
and handle the error in this action:
def routing_error
render text: "Not found, sorry", status: :not_found
end
我无法复制@matthew-savage 的结果。但是,根据 Rails guide on route globbing和this question on another StackOverflow question,我这样解决了这个问题:
路线.rb
match "*gibberish", :to => "home#routing_error"
请注意我是如何在通配符之后包含文本的。控制器很好,如上图所示:
控制器/home_controller.rb
....
def routing_error
render text: "Not found, sorry", status: :not_found
end
好例子。
路由.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