如何以正确的方式捕获连接拒绝错误?

在我的代码中,我提出了一些发布请求。如何在该调用中捕获连接拒绝错误?


   try:

        headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}

        response = requests.request("POST", local_wallet_api + "v1/wallet/get_public_keys", headers=headers)

        res = json.loads(response.text)



   except Exception as e:

        if e.errno == errno.ECONNREFUSED:

            print("connection refused")

            sys.exit(141)

我已经尝试了上面的代码,但它不起作用,因为它说e没有errno参数。有没有正确的方法来处理这种错误?


料青山看我应如是
浏览 216回答 3
3回答

慕森王

from requests.exceptions import ConnectionError   try:        headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}        response = requests.request("POST", local_wallet_api + "v1/wallet/get_public_keys", headers=headers)        res = json.loads(response.text)   except ConnectionError:        sys.exit(141)

芜湖不芜

您可以将其requests.exceptions.RequestException用作例外。例子:except requests.exceptions.RequestException as e:     # exception here有关请求例外的列表,请查看 requests.exception 文档。你可以参考这个链接。

冉冉说

看看这个。你可以得到 errno e.args[0].reason.errno。也使用这个,除了:except requests.exceptions.ConnectionError as e:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python