Skip to content

Commit cf95d81

Browse files
committed
restored from old pydanitc_v2_migration branch
1 parent 84f1e51 commit cf95d81

File tree

2 files changed

+45
-10
lines changed

2 files changed

+45
-10
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
""" osparc ERROR CODES (OEC)
2+
Unique identifier of an exception instance
3+
Intended to report a user about unexpected errors.
4+
Unexpected exceptions can be traced by matching the
5+
logged error code with that appeneded to the user-friendly message
6+
7+
SEE test_error_codes for some use cases
8+
"""
9+
10+
import re
11+
from typing import TYPE_CHECKING, Annotated
12+
13+
from pydantic import StringConstraints, TypeAdapter
14+
15+
_LABEL = "OEC:{}"
16+
_PATTERN = r"OEC:\d+"
17+
18+
if TYPE_CHECKING:
19+
ErrorCodeStr = str
20+
else:
21+
ErrorCodeStr = Annotated[
22+
str, StringConstraints(strip_whitespace=True, pattern=_PATTERN)
23+
]
24+
25+
26+
def create_error_code(exception: BaseException) -> ErrorCodeStr:
27+
return TypeAdapter(ErrorCodeStr).validate_python(_LABEL.format(id(exception)))
28+
29+
30+
def parse_error_code(obj) -> set[ErrorCodeStr]:
31+
return set(re.findall(_PATTERN, f"{obj}"))

packages/common-library/tests/test_errors_classes.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -136,24 +136,28 @@ class MyError(OsparcErrorMixin, ValueError):
136136

137137

138138
def test_missing_keys_in_msg_template_does_not_raise():
139-
class MyErrorBefore(OsparcErrorMixin, ValueError):
140-
msg_template = "{value} and {missing}"
141-
142-
with pytest.raises(KeyError, match="missing"):
143-
str(MyErrorBefore(value=42))
144-
145-
class MyErrorAfter(OsparcErrorMixin, ValueError):
139+
class MyError(OsparcErrorMixin, ValueError):
146140
msg_template = "{value} and {missing}"
147141

148-
assert str(MyErrorAfter(value=42)) == "42 and 'missing=?'"
142+
assert str(MyError(value=42)) == "42 and 'missing=?'"
149143

150144

151145
def test_exception_context():
152146
class MyError(OsparcErrorMixin, ValueError):
153147
msg_template = "{value} and {missing}"
154148

155149
exc = MyError(value=42, missing="foo", extra="bar")
156-
assert exc.error_context() == {"value": 42, "missing": "foo", "extra": "bar"}
150+
assert exc.error_context() == {
151+
"code": "ValueError.MyError",
152+
"message": "42 and foo",
153+
"value": 42,
154+
"missing": "foo",
155+
"extra": "bar",
156+
}
157157

158158
exc = MyError(value=42)
159-
assert exc.error_context() == {"value": 42}
159+
assert exc.error_context() == {
160+
"code": "ValueError.MyError",
161+
"message": "42 and 'missing=?'",
162+
"value": 42,
163+
}

0 commit comments

Comments
 (0)