Redirect on catching an exception in a method in t

2019-05-17 18:29发布

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

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.

1条回答
男人必须洒脱
2楼-- · 2019-05-17 19:01

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 then you can put



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.

查看更多
登录 后发表回答