2014-11-21 35 views
2

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

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异常与消息您无权访问此页但我想赶上可超时设计(我猜)例外,以便我可以显示默认设计消息:您的会话已过期。请重新登录以继续

任何想法?

+0

我有完全相同的问题... – 2014-11-26 23:19:55

回答

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