处理的异常分类尽可能全

在网络请求的上下文中,除了HTTP错误之外,还可能遇到多种其他类型的异常。以下是一些可能遇到的异常及其示例:

1. 网络连接异常(ConnectionError

这类异常可能发生在网络连接问题时,如无法连接到服务器。

except requests.ConnectionError as e: 
    logging.error(f"Network connection error: {e}") 

2. 超时异常(Timeout

当请求超过了预定的时间限制还没有得到响应时,会抛出超时异常。

except requests.Timeout as e: 
    logging.error(f"Request timed out: {e}") 

3. URL 异常(InvalidURL

当提供的URL格式不正确或无法解析时,会抛出URL异常。

except requests.exceptions.InvalidURL as e: 
    logging.error(f"Invalid URL provided: {e}") 

4. 请求被中断(RequestException

这是一个更一般的异常,可以捕捉以上未覆盖的其他请求相关错误。

except requests.RequestException as e: 
    logging.error(f"An error occurred during the request: {e}") 

5. JSON解析异常(JSONDecodeError

当响应体不是有效的JSON格式时,尝试解析JSON会引发此异常。

except json.JSONDecodeError as e: 
    logging.error(f"Error decoding JSON data: {e}") 

完整的改进后代码示例

将以上考虑整合,我们可以编写一个更健壮的fetch_data函数,它能够处理各种网络请求相关的异常:

import requests
import logging
import json

# 配置日志
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

def fetch_data(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # 将触发HTTP错误的异常
        return response.json()
    except requests.HTTPError as http_err:
        logging.error(f"HTTP error occured: {http_err} - Status code: {response.status_code}")
    except requests.ConnectionError as conn_err:
        logging.error(f"Network connection error: {conn_err}")
    except requests.Timeout as timeout_err:
        logging.error(f"Request timed out: {timeout_err}")
    except requests.RequestException as req_err:
        logging.error(f"An error occurred during the request: {req_err}")
    except json.JSONDecodeError as json_err:
        logging.error(f"Error decoding JSON data: {json_err}")
    except Exception as err:
        logging.error(f"An unexpected error occurred: {err}")
    return None

这个例子展示了如何全面地处理网络请求中可能遇到的各种异常,确保应用程序能够优雅地处理错误和异常情况。这种健壮的错误处理策略对于构建可靠的应用程序至关重要。

猜你喜欢

转载自blog.csdn.net/hebtu666/article/details/142142713