我正在使用 Twitter Gem,并且创建了一个长时间运行的 ruby​​ 任务。我希望它能够处理常见错误,所以我希望建立一个我应该考虑防止的错误列表(例如失败的鲸鱼 500)

这是我的代码功能的开始/结束循环:

Begin

# My (omitted) very long ruby task
# filled with Twitter API requests

rescue Errno::ENOENT
  sleep(5)
  logger.info "ENOENT error - attempting to retry"
  retry
rescue Errno::ETIMEDOUT
  sleep(5)
  logger.info " Operation timed out - attempting to retry"
  retry
rescue Errno::ECONNRESET
  sleep(5)
  logger.info "Connection reset by peer - attempting to retry"
  retry
end

你能想到任何其他错误来保护和重试吗?这是处理错误的结构良好的方法吗?我应该考虑哪些设计实现?

最佳答案

考虑在最后使用一个捕获所有异常处理程序,记录遇到的异常类型并重新引发它。您的脚本可能会在第一次失败,但至少您会找出原因。

begin

# My (omitted) very long ruby task
# filled with Twitter API requests

rescue Errno::ENOENT
  sleep(5)
  logger.info "ENOENT error - attempting to retry"
  retry
rescue Errno::ETIMEDOUT
  sleep(5)
  logger.info " Operation timed out - attempting to retry"
  retry
rescue Errno::ECONNRESET
  sleep(5)
  logger.info "Connection reset by peer - attempting to retry"
  retry
rescue # This rescues StandardError and its children
  sleep(5)
  # The next line is somewhat pseudocode, because I don't use logger
  logger.this_is_somewhat_bad "Somewhat bad exception #{$!.class} #{$!} happened - I'm giving up"
  raise
rescue Exception
  sleep(5)
  # The next line is somewhat pseudocode, because I don't use logger
  logger.omg_wtf_bbq "Really bad exception #{$!.class} #{$!} happened - I'm giving up"
  raise
end

关于ruby - Twitter Gem - 需要考虑救援吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6415713/

10-13 00:42