我正在编写一个使用普通旧的Ruby对象(PORO)从控制器中抽取授权逻辑的应用程序.
目前,我有一个名为NotAuthorized的自定义异常类,我在控制器级别rescue_from,但我很好奇地知道:Rails 4是否已经出现异常,表示没有授权操作?我通过实施这个例外来重塑轮胎吗?
澄清:提高AuthorizationException并不会发生在控制器内的任何地方,而是发生在控制器之外的完全解耦的PORO内部.该对象不知道HTTP,路由或控制器.
解决方法
Rails似乎没有将异常映射为:未经授权.
默认映射在activerecord/lib/active_record/railtie.rb中定义:
config.action_dispatch.rescue_responses.merge!( 'ActiveRecord::RecordNotFound' => :not_found,'ActiveRecord::StaleObjectError' => :conflict,'ActiveRecord::RecordInvalid' => :unprocessable_entity,'ActiveRecord::RecordNotSaved' => :unprocessable_entity )
和actionpack/lib/action_dispatch/middleware/exception_wrapper.rb:
@@rescue_responses.merge!( 'ActionController::RoutingError' => :not_found,'AbstractController::ActionNotFound' => :not_found,'ActionController::MethodNotAllowed' => :method_not_allowed,'ActionController::UnknownHttpMethod' => :method_not_allowed,'ActionController::NotImplemented' => :not_implemented,'ActionController::UnknownFormat' => :not_acceptable,'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,'ActionDispatch::ParamsParser::ParseError' => :bad_request,'ActionController::BadRequest' => :bad_request,'ActionController::ParameterMissing' => :bad_request )
您可以在应用程序的配置(或自定义Railtie)中添加自定义异常:
Your::Application.configure do config.action_dispatch.rescue_responses.merge!( 'AuthorizationException' => :unauthorized ) # ... end
或者简单地使用rescue_from.