首页 > 解决方案 > 如何在 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 错误但无法处理连接错误 如何修改我的代码以处理类型连接错误?谢谢

标签: pythonpython-3.x

解决方案


您可以通过以下方式捕获连接错误requests.exceptions.ConnectionError

但我不建议使用太多的例外,除非你特别想要。如果您使用 try catch,我建议在这里捕获异常:

try:
   re = requests.post(url, json=data, headers=headers)
   re.raise_for_status()

except Exception as e:
   print(e)

推荐阅读