Transform an exception raised by cattrs into an error message.
(
exc: Exception,
msg: str = "",
origin: Any | None = None,
typ: type | None = None,
)
| 66 | |
| 67 | |
| 68 | def transform_error( |
| 69 | exc: Exception, |
| 70 | msg: str = "", |
| 71 | origin: Any | None = None, |
| 72 | typ: type | None = None, |
| 73 | ) -> str: |
| 74 | """Transform an exception raised by cattrs into an error message.""" |
| 75 | kwargs = {} |
| 76 | if origin is not None: |
| 77 | path = getattr(origin, "__qualname__", "") |
| 78 | if hasattr(origin, "__module__"): |
| 79 | path = f"{origin.__module__}.{path}" |
| 80 | |
| 81 | if path: |
| 82 | kwargs["path"] = path |
| 83 | |
| 84 | if msg: |
| 85 | msg += ": " |
| 86 | |
| 87 | # cattrs.transform_error sets expected type as None when not a cattrs exception. |
| 88 | if typ is not None and not isinstance(exc, cattrs.BaseValidationError): |
| 89 | msg += cattrs.v.format_exception(exc, typ) |
| 90 | if path := kwargs.get("path"): |
| 91 | msg = f"{msg} @ {path}" |
| 92 | else: |
| 93 | msg += "; ".join( |
| 94 | error.removesuffix(" $").removesuffix(" @") |
| 95 | for error in cattrs.transform_error(exc, **kwargs) |
| 96 | ) |
| 97 | |
| 98 | return msg |
| 99 | |
| 100 | |
| 101 | def log_exception_only( |
no test coverage detected