我有一个使用Apartment的Rails 3.2应用程序,它用作中间件。公寓抛出Apartment::SchemaNotFound
例外,没有办法用rescue_from
的ApplicationController
拯救它。我认为我会使用config.exceptions_app
中第3点所述的this blog post,但我不能将路由器设置为异常应用程序,我假设我必须创建自己的。
所以问题是:我该如何进行?
我们故意将Apartment
保持在最低限度,以允许您自己处理异常,而无需任何特定的Rails设置。
我会做类似@jenn上面所做的事情,但我不打算设置机架环境并稍后处理它,只需在机架中完全处理响应。
例如,你可能只是想在/
上重定向回SchemaNotFound
你可以做点什么
module MyApp
class Apartment < ::Apartment::Elevators::Subdomain
def call(env)
super
rescue ::Apartment::TenantNotFound
[302, {'Location' => '/'}, []]
end
end
end
这是异常的原始处理。如果你需要在Rails方面发生更多事情,那么@ jenn的答案也应该有效。
查看Rack了解更多详情
我有一个类似的问题,另一个中间件抛出一个自定义异常,所以我根本没有看过公寓,但可能是这样的:
#app/middleware/apartment/rescued_apartment_middleware.rb
module Apartment
class RescuedApartmentMiddleware < Apartment::Middleware
def call(env)
begin
super
rescue Apartment::SchemaNotFound
env[:apartment_schema_not_found] = true # to be later referenced in your ApplicationController
@app.call(env) # the middleware call method should return this, but it was probably short-circuited by the raise
end
end
end
end
然后在你的环境中:
config.middleware.use(Apartment::RescuedApartmentMiddleware, etc)
要访问从ApplicationController或任何控制器设置的env变量:
if request.env[:apartment_schema_not_found]
#handle
end
How to rescue from a OAuth::Unauthorized exception in a Ruby on Rails application?和How do I access the Rack environment from within Rails?的组合