4
4
5
5
from pydantic import BaseModel , ValidationError
6
6
7
- from ..exceptions import InvalidEnvelopeError
7
+ from ..exceptions import InvalidEnvelopeError , SchemaValidationError
8
8
9
9
logger = logging .getLogger (__name__ )
10
10
@@ -14,28 +14,29 @@ class BaseEnvelope(ABC):
14
14
def _parse_user_dict_schema (user_event : Dict [str , Any ], schema : BaseModel ) -> Any :
15
15
if user_event is None :
16
16
return None
17
- logger .debug ("parsing user dictionary schema" )
18
17
try :
18
+ logger .debug ("parsing user dictionary schema" )
19
19
return schema (** user_event )
20
- except (ValidationError , TypeError ):
20
+ except (ValidationError , TypeError ) as e :
21
21
logger .exception ("Validation exception while extracting user custom schema" )
22
- raise
22
+ raise SchemaValidationError ( "Failed to extract custom schema" ) from e
23
23
24
24
@staticmethod
25
25
def _parse_user_json_string_schema (user_event : str , schema : BaseModel ) -> Any :
26
26
if user_event is None :
27
27
return None
28
+
28
29
# this is used in cases where the underlying schema is not a Dict that can be parsed as baseModel
29
- # but a plain string i.e SQS has plain string payload
30
- if schema == str :
30
+ # but a plain string as payload i.e. SQS: "body": "Test message."
31
+ if schema is str :
31
32
logger .debug ("input is string, returning" )
32
33
return user_event
33
- logger . debug ( "trying to parse as json encoded string" )
34
+
34
35
try :
36
+ logger .debug ("trying to parse as json encoded string" )
35
37
return schema .parse_raw (user_event )
36
- except (ValidationError , TypeError ):
37
- logger .exception ("Validation exception while extracting user custom schema" )
38
- raise
38
+ except (ValidationError , TypeError ) as e :
39
+ raise SchemaValidationError ("Failed to extract custom schema from JSON string" ) from e
39
40
40
41
@abstractmethod
41
42
def parse (self , event : Dict [str , Any ], schema : BaseModel ):
@@ -44,7 +45,7 @@ def parse(self, event: Dict[str, Any], schema: BaseModel):
44
45
45
46
def parse_envelope (event : Dict [str , Any ], envelope : BaseEnvelope , schema : BaseModel ):
46
47
if not callable (envelope ) and not isinstance (BaseEnvelope ):
47
- logger . exception ( "envelope must be a callable and instance of BaseEnvelope" )
48
- raise InvalidEnvelopeError ( "envelope must be a callable and instance of BaseEnvelope" )
48
+ raise InvalidEnvelopeError ( f "envelope must be a callable and instance of BaseEnvelope, envelope= { envelope } " )
49
+
49
50
logger .debug (f"Parsing and validating event schema, envelope={ envelope } " )
50
51
return envelope ().parse (event = event , schema = schema )
0 commit comments