简体   繁体   中英

Is there recommended way to handle Twitter API error in rails?

I'm creating a Twitter related web service. So Twitter API is called in many points in it. I know the rate limit error can be handled by rescue Twitter::Error::TooManyRequests .

But to write in every place begin and rescue syntax is little troublesome and error prone.

When the error happens I want to show a error message in view and make the twitter request method return nil .

I'm using twitter gem and using like this.

 # app/models/user.rb
 def twitter
    @twitter ||= Twitter::Client.new(oauth_token: access_token, oauth_token_secret: access_secret)
 end

How can I implement like this?

Besides this is only what comes up to my mind, if there is a better way I'll follow the instruction.

Just rescue the error and return nil in your method:

# app/models/user.rb
def twitter
  @twitter ||= Twitter::Client.new(oauth_token: access_token, oauth_token_secret: access_secret)
rescue Twitter::Error::TooManyRequests
  nil
end

Now the method itself will return nil when your error occurs.

Then in your controller, you can set the flash if the twitter method returns nil (you could also choose something more descriptive than nil).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM