0

I have the following code:

from .consts import BASE_URL, HOSTNAME_PATTERN

class GenericParseException(Exception):
    pass

def validate_hostname(value: str) -> str:
    if value.startswith("http://") or value.startswith("https://"):
        raise GenericParseException("base_url should not include the protocol (http:// or https://)")

    if not re.match(HOSTNAME_PATTERN, value):
        raise GenericParseException("Invalid hostname format.")

    return value

HostnameType = Annotated[str, AfterValidator(validate_hostname)]


class Config(BaseModel):
    api_token: str
    base_url: HostnameType = BASE_URL

class ConfigParser:
    def __init__(self, logger: LoggerInterface):
        self.logger = logger
        
    def parse(self, config: dict[str, Any]) -> Config:
        errors: List[str] = []
        try:
            model = Config(**config)
            return model
        except ValidationError as e:
            errors.extend(e.errors())
        except GenericParseException as e:
            errors.append(f"Generic validation error: {e}")
        except Exception as e:
            errors.append(f"Unexpected error: {e}")
        finally:
            if errors:
                self.logger.error({
                    'action': 'validation',
                    'status': 'failed',
                    'errors': errors
                })
                raise ConfigParseException("; ".join(str(err) for err in errors))

I trying to aggregate the errors, without success... I've tried with both AfterValidator & BeforeValidator

The expected output should be something like:

api_token - required field
base_url - base_url should not include the protocol (http:// or https://)

I'm only getting the base_url error.

Any ideas?

2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.