我们刚刚将我们的应用升级到了Rails 3.2.2,现在在处理错误时遇到了路由问题。
对于每个José Valim's blog post,我们添加了以下内容:
到config.exceptions_app = self.routes /Application.rb的配置
到match "/404", :to => "errors#not_found" /routes.rb的配置
(和适当的控制器/视图)。
问题是我们需要ourdomain.com/id来显示id的产品类别的索引页。
因此,现在ourdomain.com/404显示了我们的404页面,它应该显示id为404的类别的类别列表页面。
我们该如何解决这个问题呢?
有没有办法让应用程序在routes对每个错误进行评估之前预先加上error_
或者,可能以某种方式将config.exceptions_app设置为引用routes文件中的名称空间?
或者,我是否可以创建第二个路径集并设置config.exceptions_app = self.second_set_of_routes
谢谢!
发布于 2012-03-21 05:30:13
到目前为止,我找到了一个解决方案:
# application_controller.rb
def rescue_404
rescue_action_in_public CustomNotFoundError.new
end
def rescue_action_in_public(exception)
case exception
when CustomNotFoundError, ::ActionController::UnknownAction then
#render_with_layout "shared/error404", 404, "standard"
render template: "shared/error404", layout: "standard", status: "404"
else
@message = exception
render template: "shared/error", layout: "standard", status: "500"
end
end
def local_request?
return false
endrescue_action_in_public是Rails调用来处理大多数错误的方法。
local_request?该方法告诉Rails,如果它是本地请求,就停止执行
# config/routes.rb
match '*path', controller: 'application', action: 'rescue_404' \
unless ::ActionController::Base.consider_all_requests_local它只是说它找不到任何其他的路由来处理请求(即*path),它应该调用应用程序控制器上的rescue_404操作(上面的第一个方法)。
编辑
这个版本对我来说效果很好!尝试添加到application.rb
# 404 catch all route
config.after_initialize do |app|
app.routes.append{ match '*a', to: 'application#render_not_found' } \
unless config.consider_all_requests_local
end请参阅:https://github.com/rails/rails/issues/671#issuecomment-1780159
发布于 2012-09-20 23:48:47
我们也遇到了同样的问题--根级别的资源的错误代码与ids冲突(例如,ourdomain.com/:resource_id和ourdomain.com/404之间的冲突)。
我们修改了JoséValim的解决方案,添加了一个仅在处理异常时适用的路由约束:
# Are we handling an exception?
class ExceptionAppConstraint
def self.matches?(request)
request.env["action_dispatch.exception"].present?
end
end
MyApp::Application.routes.draw do
# These routes are only considered when there is an exception
constraints(ExceptionAppConstraint) do
match "/404", :to => "errors#not_found"
match "/500", :to => "errors#internal_server_error"
# Any other status code
match '*a', :to => "errors#unknown"
end
...
# other routes, including 'match "/:resource_id"'
end(我们昨天晚上才偶然发现了这个解决方案,所以它没有太多的老化时间。我们使用的是Rails 3.2.8)
发布于 2012-03-21 05:28:15
此路由似乎是在show_exceptions方法(see source)中硬编码的
对不起,除了将上面源代码中的第45行改为:
env["PATH_INFO"] = "/error_#{status}"(不用说,根本没有解决方案)。
不妨问问:如果你觉得实现自己的错误控制器这么简单很好,并且非常想拥有它,那么如果你的路由是yourdomain.com/RESTful/:id,那它不是更"RESTful“吗?
https://stackoverflow.com/questions/9794406
复制相似问题