import json
import logging
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
def safe_json_load(json_string):
"""
Loads a JSON string, handling potential errors with logging.
Returns the parsed JSON object or None if an error occurs.
"""
try:
data = json.loads(json_string)
return data
except json.JSONDecodeError as e:
logging.error(f"Error decoding JSON: {e}")
return None
except TypeError as e:
logging.error(f"Type error during JSON loading: {e}")
return None
except Exception as e:
logging.exception(f"Unexpected error during JSON loading: {e}")
return None
def safe_json_dump(data, indent=4):
"""
Dumps a JSON object to a string, handling potential errors with logging.
Returns the JSON string or None if an error occurs.
"""
try:
json_string = json.dumps(data, indent=indent)
return json_string
except TypeError as e:
logging.error(f"Type error during JSON dumping: {e}")
return None
except Exception as e:
logging.exception(f"Unexpected error during JSON dumping: {e}")
return None
def wrap_logic(json_object, func, *args, **kwargs):
"""
Wraps logic that operates on a JSON object, handling errors with logging.
Returns the result of the function if successful, otherwise returns None.
"""
try:
#Ensure json_object is valid (e.g., not None)
if json_object is None:
logging.warning("JSON object is None. Returning None.")
return None
result = func(json_object, *args, **kwargs)
return result
except Exception as e:
logging.exception(f"Error executing logic with JSON object: {e}")
return None
Add your comment