In software development, properly capturing and handling errors and exceptions is critical. It ensures the robustness of applications and improves user experience. Below is an example of error and exception handling, showcasing how to improve code for better error management.
Old Code Example
Suppose we have a function for fetching data from the network. Here is the old code for handling network requests:
import requests
def fetch_data(url):
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
print("Failed to fetch data")
return NoneIssues with the Code
Using
printfor Reporting Errors:printis not suitable for production environments as it does not log errors in a structured manner.It does not allow developers to respond effectively to errors.
Lack of Exception Handling:
The code does not handle potential exceptions such as network request failures or JSON parsing errors.
Improved Code
To enhance error handling, we can improve the code as follows:
import requests
import logging
# 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() # Triggers an exception 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 Exception as err:
logging.error(f"An error occurred: {err}")
return NoneExplanation of Improvements
Logging Errors:
By using the
loggingmodule instead ofprint, error messages can now be properly logged.The logging system can be further configured to manage error information with different levels and formats.
Enhanced Exception Handling:
A
try-exceptblock is used to capture possible exceptions, such as network request errors (HTTPError) and other general exceptions (Exception).This ensures the application can handle errors gracefully without crashing.
Checking HTTP Response Status:
The
response.raise_for_status()method automatically checks for HTTP error statuses, making the code cleaner and easier to maintain.
Benefits of the Improvements
With these improvements:
The function can robustly handle various error scenarios that may arise during network requests.
Errors are logged appropriately, making it easier for developers to trace and resolve issues.
These steps are crucial for improving code quality and ensuring the stability of applications.