【问题标题】:Python: Handling requests exceptions the right wayPython:以正确的方式处理请求异常
【发布时间】:2013-06-07 14:46:17
【问题描述】:

我最近从 urlib2 切换到 requests,但不知道如何处理异常。什么是最佳实践?我当前的代码看起来像这样,但没有任何好处:

try:
    response = requests.get(url)
except requests.ConnectionError , e:
    logging.error('ConnectionError = ' + str(e.code))
    return False
except requests.HTTPError , e:
    logging.error('HTTPError = ' + str(e.reason))
    return False
except requests.Timeout, e:
    logging.error('Timeout')
    return False
except requests.TooManyRedirects:
    logging.error('TooManyRedirects')
    return False
except Exception:
    import traceback
    logging.error('generic exception: ' + traceback.format_exc())
    return False

【问题讨论】:

  • 取决于你的目标是什么。您想了解每个特定异常,还是只想检测任何故障?
  • 不,我不想知道每个特定的异常。什么是常见做法?

标签: python django exception error-handling request


【解决方案1】:

既然作为评论看起来很糟糕,你有没有试过:

try:
    # some code
except Exception as e:
    print e

【讨论】:

  • 这似乎可行,但很难测试所有错误。谢谢!我会尝试多玩一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
相关资源
最近更新 更多