1. import json
  2. import logging
  3. logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
  4. def safe_json_load(json_string):
  5. """
  6. Loads a JSON string, handling potential errors with logging.
  7. Returns the parsed JSON object or None if an error occurs.
  8. """
  9. try:
  10. data = json.loads(json_string)
  11. return data
  12. except json.JSONDecodeError as e:
  13. logging.error(f"Error decoding JSON: {e}")
  14. return None
  15. except TypeError as e:
  16. logging.error(f"Type error during JSON loading: {e}")
  17. return None
  18. except Exception as e:
  19. logging.exception(f"Unexpected error during JSON loading: {e}")
  20. return None
  21. def safe_json_dump(data, indent=4):
  22. """
  23. Dumps a JSON object to a string, handling potential errors with logging.
  24. Returns the JSON string or None if an error occurs.
  25. """
  26. try:
  27. json_string = json.dumps(data, indent=indent)
  28. return json_string
  29. except TypeError as e:
  30. logging.error(f"Type error during JSON dumping: {e}")
  31. return None
  32. except Exception as e:
  33. logging.exception(f"Unexpected error during JSON dumping: {e}")
  34. return None
  35. def wrap_logic(json_object, func, *args, **kwargs):
  36. """
  37. Wraps logic that operates on a JSON object, handling errors with logging.
  38. Returns the result of the function if successful, otherwise returns None.
  39. """
  40. try:
  41. #Ensure json_object is valid (e.g., not None)
  42. if json_object is None:
  43. logging.warning("JSON object is None. Returning None.")
  44. return None
  45. result = func(json_object, *args, **kwargs)
  46. return result
  47. except Exception as e:
  48. logging.exception(f"Error executing logic with JSON object: {e}")
  49. return None

Add your comment