capturing errors?

0 views
Skip to first unread message

Alex

unread,
Jul 16, 2008, 8:27:24 PM7/16/08
to twitter4r-users
What's the best way to capture error messages without it crashing your
whole app or console session?

For example, if I try to post to an account where I don't have the
correct username or password, my app crashes as follows:
...client/base.rb:39:in `raise_rest_error': Unauthorized
(Twitter::RESTError)

I'd appreciate your help.

Thanks.

S Potter

unread,
Jul 17, 2008, 12:01:01 AM7/17/08
to twitter...@googlegroups.com
Hi Alex,

You will need to handle the exceptions that are raised by the API. If
you are new to Ruby you should refer to the following Ruby exception
handling documentation:
http://ruby.activeventure.com/programmingruby/book/tut_exceptions.html

For example, you might do something like this around authenticated
calls to the Twitter::Client object you create:

begin
client.status(:post, "Jane Eyre rocks!")
rescue Twitter::RESTError => re
puts re.inspect
# try to resolve error by inspecting the code of the RESTError or something
end

Of course, you can create a helper method that takes a block that will
clean up after common errors, so you do not need to open up
begin/rescue blocks all the time in your code. Something roughly
like:

def twitter_block(&block)
begin

rescue Twitter::RESTError => re
case re.code
when '400'
# usually means you made too many API calls in a time period and
Twitter.com blocked you, so report that appropriately to your
end-users
when '503'
# means that Twitter.com is down
when '401'
# means you have the wrong credentials - check your login/password combo
when '403'
# means you are trying to do something that Twitter.com will not allow
# e.g. direct messaging a user that isn't your friend or something
end
end
end

HTH,
Susan

S Potter

unread,
Jul 17, 2008, 12:02:50 AM7/17/08
to twitter...@googlegroups.com
Sorry I forgot one line, so it doesn't make sense as previously sent.
Below is the corrected code:

> def twitter_block(&block)
> begin
> block.call if block_given? # line that was added to make sense


> rescue Twitter::RESTError => re
> case re.code
> when '400'
> # usually means you made too many API calls in a time period and
> Twitter.com blocked you, so report that appropriately to your
> end-users
> when '503'
> # means that Twitter.com is down
> when '401'
> # means you have the wrong credentials - check your login/password combo
> when '403'
> # means you are trying to do something that Twitter.com will not allow
> # e.g. direct messaging a user that isn't your friend or something
> end
> end
> end

--
mailto:m...@susanpotter.net
www:http://susanpotter.net
blog:http://snakesgemscoffee.susanpotter.net
linkedin:http://www.linkedin.com/in/susanpotter

Reply all
Reply to author
Forward
0 new messages