【问题标题】:Custom error handling and cancan自定义错误处理和 cancan
【发布时间】:2013-12-04 08:03:26
【问题描述】:

我正在尝试实现自定义错误处理以及使用 CanCan。当用户到达他们不允许去的区域时,会抛出 CanCan::AccessDenied 错误,并且应该将它们发送到根 url。相反,“rescue_from Exception”捕获 CanCan::AccessDenied 并且用户收到 500 错误。我做错了什么?

#application_controller.rb
rescue_from CanCan::AccessDenied do |exception|
  redirect_to main_app.root_url, :alert => exception.message
end

rescue_from Exception,
  :with => :render_error
rescue_from Mongoid::Errors::DocumentNotFound,
  :with => :render_not_found
rescue_from ActionController::RoutingError,
  :with => :render_not_found
rescue_from ActionController::UnknownController,
  :with => :render_not_found
rescue_from AbstractController::ActionNotFound,
  :with => :render_not_found


def render_not_found(exception)
  render :template => "/errors/404.html",
       :layout => 'errors.html',
       :status => 404
end

def render_error(exception)
  render :template => "/errors/500.html",
       :layout => 'errors.html',
       :status => 500
end

【问题讨论】:

    标签: ruby-on-rails error-handling cancan


    【解决方案1】:

    您是否尝试过从异常/错误中重新排序rescue_from,首先更通用,稍后更具体,例如

    rescue_from StandardError,
      :with => :render_error
    rescue_from Mongoid::Errors::DocumentNotFound,
      :with => :render_not_found
    rescue_from ActionController::RoutingError,
      :with => :render_not_found
    rescue_from ActionController::UnknownController,
      :with => :render_not_found
    rescue_from AbstractController::ActionNotFound,
      :with => :render_not_found
    rescue_from CanCan::AccessDenied do |exception|
      redirect_to main_app.root_url, :alert => exception.message
    end
    

    注意:您可能希望将通用异常替换为 StandardError。

    【讨论】:

    • 这个解决方案对我有用。正如您所指出的,Rails 文档清楚地表明顺序很重要。
    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 2013-02-12
    • 2011-01-29
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多