捕获请求异常是在网络请求过程中经常遇到的问题,可以使用try-except语句来捕获异常并进行相应的处理。下面是一个简单的代码示例:
import requests
url = 'http://example.com'
try:
response = requests.get(url)
response.raise_for_status() # 检查响应是否成功
# 在这里处理正常的响应数据
except requests.exceptions.RequestException as e:
# 处理请求异常
print('请求异常:', e)
except requests.exceptions.HTTPError as e:
# 处理HTTP错误
print('HTTP错误:', e)
except requests.exceptions.ConnectionError as e:
# 处理连接错误
print('连接错误:', e)
except requests.exceptions.Timeout as e:
# 处理超时错误
print('超时错误:', e)
except requests.exceptions.TooManyRedirects as e:
# 处理太多重定向错误
print('太多重定向错误:', e)
在这个示例中,首先使用requests.get()
方法发送一个GET请求,并将响应保存在response
变量中。然后,使用response.raise_for_status()
方法检查响应是否成功,如果不成功会抛出一个requests.exceptions.HTTPError
异常。
在try
块中,我们可以处理不同类型的请求异常。例如,requests.exceptions.ConnectionError
表示连接错误,requests.exceptions.Timeout
表示超时错误,requests.exceptions.TooManyRedirects
表示太多重定向错误等等。当捕获到异常时,可以根据具体情况进行相应的处理,例如打印错误信息或者进行重试操作。
需要注意的是,这只是一个简单的示例,实际应用中可能会有更多的异常类型需要处理。另外,根据具体的网络请求库,可能会有不同的异常类和处理方式。因此,具体的代码实现可能会有所不同。
下一篇:不获取使用Go发送的表单数据