1import re
2from typing import Any
3
4
5SPLIT_RE = re.compile(r'[\.\[\]]+')
6
7
8class JsonSchemaException(ValueError):
9 """
10 Base exception of ``fastjsonschema`` library.
11 """
12
13
14class JsonSchemaValueException(JsonSchemaException):
15 """
16 Exception raised by validation function. Available properties:
17
18 * ``message`` containing human-readable information what is wrong
19 (e.g. ``data.property[index] must be smaller than or equal to 42``),
20 * invalid ``value`` (e.g. ``60``),
21 * ``name`` of a path in the data structure (e.g. ``data.property[index]``),
22 * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``),
23 * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``),
24 * ``rule`` which the ``value`` is breaking (e.g. ``maximum``)
25 * and ``rule_definition`` (e.g. ``42``).
26
27 .. versionchanged:: 2.14.0
28 Added all extra properties.
29 """
30
31 def __init__(
32 self,
33 message: str,
34 value: Any = None,
35 name: str | None = None,
36 definition: Any = None,
37 rule: str | None = None,
38 ) -> None:
39 super().__init__(message)
40 self.message = message
41 self.value = value
42 self.name = name
43 self.definition = definition
44 self.rule = rule
45
46 @property
47 def path(self) -> list[str]:
48 return [item for item in SPLIT_RE.split(self.name or '') if item != '']
49
50 @property
51 def rule_definition(self) -> Any:
52 if not self.rule or not self.definition:
53 return None
54 return self.definition.get(self.rule)
55
56
57class JsonSchemaValuesException(JsonSchemaException):
58 """
59 Exception raised by validation function when ``fast_fail`` is turned off.
60 Available properties:
61
62 * ``errors`` containing all :any:`JsonSchemaValueException` found in the data
63 * and ``message`` joining messages of all the errors.
64 """
65
66 def __init__(self, errors: list[JsonSchemaValueException]) -> None:
67 self.message = '; '.join(error.message for error in errors)
68 super().__init__(self.message)
69 self.errors = errors
70
71
72class JsonSchemaDefinitionException(JsonSchemaException):
73 """
74 Exception raised by generator of validation function.
75 """