python-2.7 - 捕获请求异常的问题
问题描述
我正在向网络服务器创建删除请求并尝试捕获如下异常:
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)
但是 delete 没有被处理和response.status_code
打印400
,但是错误处理不起作用。任何想法为什么错误处理在那里不起作用?
解决方案
如果你想捕获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)
推荐阅读
- php - 注释行之间的匹配
- java - 如何使用 SoapUi 和 Spring boot 自动化 API 测试
- .net-core - 为这项工作准备代理。代理未在 Devops 上运行
- git - 将工作树转换回正常的 git 结构
- javascript - React Native 在组件之间添加间距
- java - 如何在 Java 中使用 selenium Web 驱动程序查找突出显示的文本?
- c# - 使用 Entity Framework Core 编写计算成员
- python - 如何使用python用大小为(8,8)的二维数组替换数组最后一列的前8个元素(大小=(8,8,3))
- grep - 避免在 grep 结果中使用破折号
- flutter - 如何为 gitlab 代码编辑器添加 Flutter 支持