在模型中的方法中捕获异常时进行重定向 [英] Redirect on catching an exception in a method in the model

查看:71
本文介绍了在模型中的方法中捕获异常时进行重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Authlogic-connect连接各种服务提供商. user.rb

I am using Authlogic-connect to connect various service providers. There is a method in user.rb

def complete_oauth_transaction
      token = token_class.new(oauth_token_and_secret)
      old_token = token_class.find_by_key_or_token(token.key, token.token)
      token = old_token if old_token

      if has_token?(oauth_provider)
        self.errors.add(:tokens, "you have already created an account using your #{token_class.service_name} account, so it")
      else
        self.access_tokens << token
      end
    end

已经添加了服务提供商后,是否给出了has_token中所述的错误?方法和分页符.我需要将应用程序重定向到同一页面并刷新错误.我该怎么做呢?我已经在自己的user.rb中覆盖了该方法,以便可以更改代码.

When a service provider is already added it gives the error as stated in the has_token? method and the page breaks. I need to redirect the app to the same page and flash the error. How do i do this? I have overridden the method in my own user.rb so that I can change the code.

推荐答案

嗯,您可以放置​​一个处理has_token错误的方法吗?引发,并告诉您的控制器重定向该确切错误.在您的控制器中是这样的:

Hmm, well you could put a method that handles the error that has_token? throws, and tell your controller to redirect that exact error. something like this in your controller:

rescue_from OauthError::RecordNotFound, :with => :deny_access 然后你可以放



def deny_access
  redirect_to your_view_path, :alert => "Too bad sucker" #some flash message
end

或者您可以在控制器中执行以下操作:

Or you could do something like this in the controller:


if complete_oauth_transaction.errors.present?
  redirect_to your_view_path
else
  # continue on with the normal code here
end

这是一般处理错误的方法.您的确切代码会有所不同,因为这就是我们所要做的.

This is how you could generically handle errors. Your exact code will vary, as this is all we have to go off of.

这篇关于在模型中的方法中捕获异常时进行重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆