12

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!

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

3 Comments

Could you kindly explain why rescue Exception should be avoided when possible (and just rescue alone should be used)? Also, when would it not be possible to avoid specifying Exception?
rescue on its own rescues from StandardError and its children which is all you need 99% of the time, whereas rescue Exception goes higher up the chain and rescues from signals, system exits, no memory errors, and script errors. Unless you are using rescue Exception for a particular reason, you should not use it.
what is the convention for informing the client about these exceptions? Do we suppress them and simply return Internal server error or something like that or Do we propagate these exception messages up to the controller which will send the exception message as a response to the client?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.