Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/serde/exceptions.py: 68%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

34 statements  

1""" 

2This module contains `Exception` classes that are used in Serde. 

3""" 

4 

5from contextlib import contextmanager 

6 

7 

8__all__ = [ 

9 'ContextError', 

10 'MissingDependencyError', 

11 'SerdeError', 

12 'ValidationError', 

13] 

14 

15 

16class SerdeError(Exception): 

17 """ 

18 A generic error that can occur in this package. 

19 

20 Args: 

21 message (str): a message describing the error that occurred. 

22 """ 

23 

24 @property 

25 def message(self): 

26 """ 

27 A message describing the error that occurred. 

28 """ 

29 return self.args[0] 

30 

31 def __repr__(self): 

32 """ 

33 Return the canonical string representation of this error. 

34 """ 

35 return '<{}.{}: {}>'.format( 

36 self.__class__.__module__, self.__class__.__name__, str(self.message) 

37 ) 

38 

39 

40class ContextError(SerdeError): 

41 """ 

42 Raised when `Fields <serde.fields.Field>` are used in the wrong context. 

43 """ 

44 

45 

46class MissingDependencyError(SerdeError): 

47 """ 

48 Raised when a dependency is missing. 

49 """ 

50 

51 

52class ValidationError(SerdeError): 

53 """ 

54 Raised when any `~serde.Model` stage fails. 

55 

56 Args: 

57 message: a message describing the error that occurred. 

58 value: the value which caused this error. 

59 """ 

60 

61 def __init__(self, message, value=None): 

62 """ 

63 Create a new `SerdeError`. 

64 """ 

65 super(SerdeError, self).__init__(message) 

66 self.value = value 

67 self._fields = [] 

68 

69 def messages(self): 

70 """ 

71 A dictionary or list of messages that corresponds to the model structure. 

72 """ 

73 from serde.fields import Field 

74 

75 d = self.message 

76 for field in self._fields: 

77 # Avoids tags which might not have `_serde_name` 

78 if isinstance(field, Field): 

79 d = {field._serde_name: d} 

80 elif isinstance(field, (str, int)): 

81 d = {field: d} 

82 return d 

83 

84 def __str__(self): 

85 """ 

86 Return a string representation of this error. 

87 """ 

88 return str(self.messages()) 

89 

90 

91@contextmanager 

92def add_context(field): 

93 """ 

94 A context manager to add the field context to a ValidationError. 

95 

96 Args: 

97 field (~serde.fields.Field): the field context to add. 

98 """ 

99 try: 

100 yield 

101 except ValidationError as e: 

102 e._fields.append(field) 

103 raise