[英]How to use rescue_from with Rails 6?
Apparently rescue_from
is supposed to catch Exceptions, but this does not work as expected:显然, rescue_from
应该捕获异常,但这不能按预期工作:
class ApplicationController < ActionController::Base
rescue_from ActionController::RoutingError, with: :not_found
def not_found
text: 'Not found'
end
end
Spec:规格:
specify 'Not found' do
visit '/zzz'
expect(page.status_code).to eq 200
end
Failure/Error: visit '/zzz'
ActionController::RoutingError:
No route matches [GET] "/zzz"
Same behavior in development environment.在开发环境中的行为相同。
However, rescuing other errors such as RuntimeError
does work as expected.但是,抢救其他错误(例如RuntimeError
)确实可以按预期工作。
Docs: https://apidock.com/rails/v6.0.0/ActiveSupport/Rescuable/ClassMethods/rescue_from文档: https://apidock.com/rails/v6.0.0/ActiveSupport/Rescuable/ClassMethods/rescue_from
Rails 6.0.2导轨 6.0.2
Why can't RoutingError
be used with rescue_from
?为什么RoutingError
不能与rescue_from
一起使用? Is RoutingError raised in middleware or by the router before the controller is called?在调用 controller 之前,RoutingError 是在中间件中还是由路由器引发的? Is there another way to catch RoutingError
?还有其他方法可以捕获RoutingError
吗?
Router errors are raised before reaching a controller, you could have a wildcard route to match anything that's not matched by other routes at the end of the routes.rb file an point that route to a specific controller action.在到达 controller 之前会引发路由器错误,您可以有一个通配符路由来匹配 routes.rb 文件末尾的其他路由不匹配的任何内容,以及路由到特定 controller 操作的点。
Something like:就像是:
match '*foo', to: 'application#not_found'
(Didn't try that, you may need to tweak it a little but I think the idea is clear) (没试过,你可能需要稍微调整一下,但我认为这个想法很清楚)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.