cancancan + devise:处理超时异常

时间:2014-11-21 11:49:45

标签: ruby-on-rails ruby-on-rails-3 devise cancancan

在我的rails 3应用程序中,我使用了设计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异常您无权访问此页面但我想抓住可超时的Devise(我猜)异常,以便我可以显示默认设计消息:您的会话已过期。请再次登录以继续

有什么想法吗?

1 个答案:

答案 0 :(得分: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