re.error not wrapped in ValidationError when invalid regex is provided for Pattern field
mrburrito opened this issue · comments
I have a data model that accepts a user-provided regular expression with the model defined as:
@dataclass
class Regex:
pattern: Pattern = field(metadata=schema(min_len=1))
group: int = field(default=0, metadata=schema(min=0))
I have several validation tests to confirm expected behavior and, when I try to verify that a pattern of "(unclosed"
results in a ValidationError
, my tests fail because the re.error
thrown by re.compile()
is being raised instead.
I tried defining a custom deserializer for Pattern, but it isn't getting executed
@deserializer
def to_pattern(pattern: str) -> Pattern:
try:
return re.compile(pattern)
except re.error as err:
raise ValidationError(f"invalid regex pattern '{pattern}': {err}")
Not sure if I'm doing something wrong with the configuration or if the default deserializer for re.Pattern
needs to be updated.
This works as a workaround, but was hoping to have the more semantically correct typing.
@dataclass
class Regex:
pattern: str = field(metadata=schema(min_len=1))
group: int = field(default=0, metadata=schema(min=0))
@validator
def check_regex_pattern(self):
try:
re.compile(self.pattern)
except re.error as err:
raise ValidationError(f"invalid regex pattern '{self.pattern}': {err}")