python发送http消息时的经典异常处理

你可以在函数中加入 try-except 块。这不仅可以捕获异常,还可以提供有用的错误信息给用户,确保程序的稳定性和可靠性。

def send_message(endpoint, api_key, message):
    """发送消息给 http 服务,并接收响应"""
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    data = {
        'message': message
    }
    try:
        response = requests.post(endpoint, headers=headers, json=data)
        response.raise_for_status()  # 会抛出HTTPError,如果响应状态码不是200
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        return {'error': f'HTTP error occurred: {http_err}'}
    except requests.exceptions.ConnectionError as conn_err:
        return {'error': f'Connection error occurred: {conn_err}'}
    except requests.exceptions.Timeout as timeout_err:
        return {'error': f'Timeout error occurred: {timeout_err}'}
    except requests.exceptions.RequestException as req_err:
        return {'error': f'Error occurred: {req_err}'}
    except Exception as e:
        return {'error': f'An unexpected error occurred: {e}'}

异常处理的各种情况:

  • HTTPError:如果服务器返回非2xx响应,会抛出此异常。这里使用 response.raise_for_status() 方法检查响应状态。
  • ConnectionError:如果网络连接出现问题,则抛出此异常。
  • Timeout:如果请求超时,这通常是因为服务器没有在预期时间内响应。
  • RequestException:涵盖了上述未特别指出的其他所有请求相关的异常。
  • Exception:用作一种通用的异常捕获,以防出现预期之外的错误。
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值