2

在我的 rails 3 应用程序中,我使用的是 devise 3.2.4 和 cancancan 1.9.2。我的问题是关于可以正常工作的可超时设计模块,但我无法挽救正确的异常,以便我可以向用户显示正确的通知。

我的application_controller.rb包含:

rescue_from Exception do |exception|
  unless Rails.env.production?
    raise exception
  else
    redirect_to :back, :flash => { :error => exception.message } 
  end
end

# https://github.com/ryanb/cancan/wiki/exception-handling
rescue_from CanCan::AccessDenied do |exception|
  flash[:error] = exception.message
  respond_to do |wants|
    wants.html { redirect_to main_app.root_url }
    wants.js { render :file => "shared/update_flash_messages" }
  end
end

每当会话到期时,我都可以CanCan::AccessDenied使用消息挽救一个通用异常您无权访问此页面,但我想捕获一个可超时的设计(我猜)异常,以便我可以显示默认的设计消息:您的会话已过期. 请重新登录以继续

任何想法?

4

1 回答 1

0

当会话超时时, 的值flash[:alert]设置为:timeout,默认情况下定义在config/locales/devise.en.yml.

因此exception,与其阅读来自 的消息,不如尝试阅读flash[:alert]并让您的应用做出相应的反应。例如,这是我在应用程序中使用的代码:

rescue_from CanCan::AccessDenied do |exception|
  if user_signed_in?
    # Blank page with an error message
    flash.now.alert = exception.message
    render text: '', layout: true, status: 403
  else
    # Redirect to login screen and display the message
    redirect_to new_user_session_path, :notice => flash[:alert] || "You must login first"
  end
end
于 2014-11-26T23:56:32.710 回答