In the context of network requests, there are various types of exceptions that might occur beyond HTTP errors. Below is a list of potential exceptions with examples:
1. Network Connection Errors (ConnectionError)
These exceptions may occur when there is a problem with the network connection, such as being unable to connect to the server.
except requests.ConnectionError as e:
logging.error(f"Network connection error: {e}")2. Timeout Exceptions (Timeout)
Timeout exceptions are raised when a request exceeds the predefined time limit without receiving a response.
except requests.Timeout as e:
logging.error(f"Request timed out: {e}")3. URL Exceptions (InvalidURL)
URL exceptions occur when the provided URL is improperly formatted or cannot be resolved.
except requests.exceptions.InvalidURL as e:
logging.error(f"Invalid URL provided: {e}")4. Interrupted Requests (RequestException)
This is a more general exception that captures other request-related errors not covered above.
python複製程式碼except requests.RequestException as e:
logging.error(f"An error occurred during the request: {e}")5. JSON Parsing Exceptions (JSONDecodeError)
This exception is raised when the response body is not valid JSON, causing the JSON parser to fail.
except json.JSONDecodeError as e:
logging.error(f"Error decoding JSON data: {e}")Improved Example Code
Integrating these considerations, we can write a more robust fetch_data function that handles a wide range of exceptions during network requests:
import requests
import logging
import json
# Configure logging
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() # Trigger exceptions for HTTP errors
return response.json()
except requests.HTTPError as http_err:
logging.error(f"HTTP error occurred: {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 NoneKey Takeaways
This example demonstrates how to comprehensively handle various exceptions that may occur during network requests, ensuring the application can gracefully manage errors. Implementing such robust error-handling strategies is crucial for building reliable applications.