Skip to content
This repository was archived by the owner on Feb 14, 2025. It is now read-only.

Commit

Permalink
nicer exception message
Browse files Browse the repository at this point in the history
  • Loading branch information
boonhapus committed Jan 8, 2025
1 parent 8113588 commit ee930d9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 42 deletions.
67 changes: 28 additions & 39 deletions src/thoughtspot_tml/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Optional
import dataclasses
from typing import TYPE_CHECKING, Optional

from yaml import error

if TYPE_CHECKING:
from collections.abc import Iterable
from pathlib import Path

from yaml import error

from thoughtspot_tml.types import GUID, TMLObject


Expand Down Expand Up @@ -41,50 +40,40 @@ class TMLDecodeError(TMLError):
Raised when a TML object cannot be instantiated from input data.
"""

def __init__(
self,
tml_cls: type[TMLObject],
*,
message: Optional[str] = None,
data: Optional[dict[str, Any]] = None,
path: Optional[Path] = None,
problem_mark: Optional[error.Mark] = None,
): # pragma: no cover
def __init__(self, tml_cls: type[TMLObject], *, exc: Exception, document: str, filepath: Optional[Path] = None):
self.tml_cls = tml_cls
self.message = message
self.data = data
self.path = path
self.problem_mark = problem_mark
self.parent_exc = exc
self.document = document
self.filepath = filepath

def __str__(self) -> str:
lines = []
class_name = self.tml_cls.__name__
def with_filepath(self, filepath) -> TMLDecodeError:
"""Add the file which generated the exception."""
self.filepath = filepath
return self

if self.message is not None:
lines.append(self.message)
def __str__(self) -> str:
lines: list[str] = []

if self.data is not None:
lines.append(f"supplied data does not produce a valid TML ({class_name}) document")
fields = {f.name for f in dataclasses.fields(self.tml_cls)}
data = set(self.data)
if isinstance(self.parent_exc, TypeError):
_, _, attribute = str(self.parent_exc).partition(" unexpected keyword argument ")
lines.append(f"Unrecognized attribute in the TML spec: {attribute}")

if data.difference(fields):
extra = ", ".join([f"'{arg}'" for arg in data.difference(fields)])
lines.append(f"\ngot extra data: {extra}")
if self.filepath is not None:
lines.append("\n")
lines.append(f"File '{self.filepath}' may not be a valid {self.tml_cls.__name__} file")

if self.path is not None:
lines.append(f"'{self.path}' is not a valid TML ({class_name}) file")
if isinstance(self.parent_exc, error.MarkedYAMLError):
if mark := self.parent_exc.problem_mark:
lines.append("\n")
lines.append(f"Syntax error on line {mark.line + 1}, around column {mark.column + 1}")

if self.problem_mark is not None:
err_line = self.problem_mark.line + 1
err_column = self.problem_mark.column + 1
snippet = self.problem_mark.get_snippet()
lines.append(f"\nsyntax error on line {err_line}, around column {err_column}")
if snippet := mark.get_snippet():
lines.append(snippet)

if snippet is not None:
lines.append(snippet)
if not lines:
lines.append(str(self.parent_exc))

return "\n".join(lines)
return "\n".join(lines).strip()


class TMLDisambiguationError(TMLError):
Expand Down
6 changes: 3 additions & 3 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def _():
with raises(TMLDecodeError) as exc:
Answer.loads(tml_document="😅: INVALID")

assert "supplied data does not produce a valid TML (Answer) document" in str(exc.raised)
assert "Unrecognized attribute in the TML spec:" in str(exc.raised)


@test("TMLDecodeError on invalid file input")
Expand All @@ -23,5 +23,5 @@ def _():
with raises(TMLDecodeError) as exc:
Answer.load(path=fp)

assert "is not a valid TML (Answer) file" in str(exc.raised)
assert "syntax error on line 2, around column 9" in str(exc.raised)
assert "may not be a valid Answer file" in str(exc.raised)
assert "Syntax error on line 2, around column 9" in str(exc.raised)

0 comments on commit ee930d9

Please sign in to comment.