util.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from __future__ import annotations
  2. from wandb.proto import wandb_internal_pb2 as pb
  3. from . import AuthenticationError, CommError, Error, UnsupportedError, UsageError
  4. to_exception_map = {
  5. pb.ErrorInfo.UNKNOWN: Error,
  6. pb.ErrorInfo.COMMUNICATION: CommError,
  7. pb.ErrorInfo.AUTHENTICATION: AuthenticationError,
  8. pb.ErrorInfo.USAGE: UsageError,
  9. pb.ErrorInfo.UNSUPPORTED: UnsupportedError,
  10. }
  11. from_exception_map = {v: k for k, v in to_exception_map.items()}
  12. class ProtobufErrorHandler:
  13. """Converts protobuf errors to exceptions and vice versa."""
  14. @staticmethod
  15. def to_exception(error: pb.ErrorInfo) -> Error | None:
  16. """Convert a protobuf error to an exception.
  17. Args:
  18. error: The protobuf error to convert.
  19. Returns:
  20. The corresponding exception.
  21. """
  22. if not error.SerializeToString():
  23. return None
  24. if error.code in to_exception_map:
  25. return to_exception_map[error.code](error.message)
  26. return Error(error.message)
  27. @classmethod
  28. def from_exception(cls, exc: Error) -> pb.ErrorInfo:
  29. """Convert an wandb error to a protobuf error message.
  30. Args:
  31. exc: The exception to convert.
  32. Returns:
  33. The corresponding protobuf error message.
  34. """
  35. if not isinstance(exc, Error):
  36. raise TypeError("exc must be a subclass of wandb.errors.Error")
  37. code = None
  38. for subclass in type(exc).__mro__:
  39. if subclass in from_exception_map:
  40. code = from_exception_map[subclass] # type: ignore
  41. break
  42. return pb.ErrorInfo(code=code, message=str(exc)) # type: ignore