【问题标题】:Issues with catching requests exceptions捕获请求异常的问题
【发布时间】:2020-05-06 09:13:31
【问题描述】:

我正在向网络服务器创建删除请求并尝试捕获如下异常:

 try:
    response = req.delete(path, auth=HTTPBasicAuth(config.user(), config.password()), params=params, headers=headers, verify=True)
except requests.HTTPError as he:
    raise SystemExit(he)
except requests.ConnectionError as ce:
    raise SystemExit(ce)
except requests.URLRequired as ue:
    raise SystemExit(ue)
except requests.Timeout as te:
    raise SystemExit(te)
except requests.RequestException as err:
    print('Undefined error: ', err)

print(response.status_code)

但删除未处理,response.status_code 打印 400,但错误处理不起作用。任何想法为什么错误处理在那里不起作用?

【问题讨论】:

    标签: python-2.7 python-requests


    【解决方案1】:

    如果你想捕获 http 错误(例如 401 Unauthorized)来引发异常,你需要调用 Response.raise_for_status。如果响应是 http 错误,则会引发 HTTPError。

    try:
        response = req.delete(path, auth=HTTPBasicAuth(config.user(), config.password()), params=params, headers=headers, verify=True)
    except requests.HTTPError as he:
        raise SystemExit(he)
    

    【讨论】:

      猜你喜欢
      • 2011-03-16
      • 2014-01-20
      • 2013-03-14
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      相关资源
      最近更新 更多