How to handle errors/exceptions when calling an external API in Ruby on Rails?

I'm interacting with CampaignMonitor's API using the ruby wrapper (createsend-ruby) and I'm just wondering what you'd recommend as far as error/exception handling. I was thinking of just using begin/rescue/end as follows, but I just want to know if there are any better techniques for this sort of thing (when you're dealing with a 3rd-party API).

begin
  list_id = CreateSend::List.create client_id, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page
rescue Exception => e
  logger.error "[error] CampaignMonitor error: #{e}"
  return false
end

For instance, would you try to catch specific exceptions and deal with them individually?

rescue CreateSend::BadRequest => e

Or is this just a matter of individual preference and/or app requirements?

Thank you for your time!


I typically start with a single exception to catch them all and go from there. If there is a particular error that comes up often or needs to be handled differently than another, just add another rescue block above your bottom one so the exception gets caught there. You're doing it right :)

Avoid rescue Exception when possible, a simple rescue should do the trick.

Just to clarify, you can have any number of rescues as well as an ensure:

begin
  do_something
rescue CS::BadRequest => e
  logger.error "..."
rescue CS::TimeoutError => e
  do_something_that_retries
rescue => e
  logger.error "..."
ensure
  send_email_to_admin
end
链接地址: http://www.djcxy.com/p/25872.html

上一篇: Timeout :: Error在Ruby中无法挽救

下一篇: 在Ruby on Rails中调用外部API时如何处理错误/异常?