Python:以正确的方式处理请求异常

时间:2013-06-07 14:46:18

标签: python django exception error-handling request

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

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

1 个答案:

答案 0 :(得分:-2)

因为评论看起来很糟糕,你试过了吗?

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