你可以在函数中加入 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:用作一种通用的异常捕获,以防出现预期之外的错误。