python - 如何在 python 中使用 request.post() 方法处理异常
问题描述
您好我正在使用以下代码
def request_task(url, data, headers):
try:
re = requests.post(url, json=data, headers=headers)
re.raise_for_status()
except requests.exceptions.HTTPError as e:
print (e.response.text)
我能够处理 http 错误但无法处理连接错误 如何修改我的代码以处理类型连接错误?谢谢
解决方案
您可以通过以下方式捕获连接错误requests.exceptions.ConnectionError
但我不建议使用太多的例外,除非你特别想要。如果您使用 try catch,我建议在这里捕获异常:
try:
re = requests.post(url, json=data, headers=headers)
re.raise_for_status()
except Exception as e:
print(e)
推荐阅读
- elasticsearch - Elasticsearch:自定义分析器中 synonym_graph 和停止过滤器之间的意外交互
- ssl - 如何使用 scapy 解密从 pcap 文件读取的 TLS 流量?
- salesforce-marketing-cloud - 我正在尝试过滤所有订阅者中的订阅者,以识别通过创建配置文件属性从哪个 MID 创建订阅者
- java - Java sftpChannel put error (系统找不到指定的路径)
- iframe - 腾讯(视频)在 iframe 中做了什么讨厌的事情?
- java - 当属性文件没有值时,我有不想创建的 bean 列表,如何实现?
- javascript - Chartjs 折线图 - 数据的数组数组
- c - 使用结构的年度学生计划
- c# - 将 FormFile 转换为流
- python-3.x - SLURM 工作。NameError:名称'python3'未定义