Create a custom Python exception with a custom message and extra attributes.
A custom exception is a class that inherits from Exception, or from a more specific built-in error type.
class ValidationError(ValueError):
def __init__(self, field, message):
super().__init__(field + ': ' + message)
self.field = field
self.message = message
try:
raise ValidationError('email', 'must contain @')
except ValidationError as err:
print(err) # email: must contain @
print(err.field) # email
print(isinstance(err, ValueError)) # True
The class inherits from ValueError rather than from Exception, and that is the important design decision. It means that callers who already handle ValueError, which plenty of validation code does, will catch your error as well without knowing that it exists. Deriving from a built-in error is how you fit your error into an existing hierarchy instead of creating a separate island of its own.
The custom __init__ builds a message that includes the field name, hands that message to super().__init__, and then stores the field and the plain message on the instance. Calling super().__init__ is what makes str(err) work, so the error reads properly in a traceback while it still carries structured data for code that wants to use it.
Two habits are worth keeping. Store the structured data on the instance instead of only inside the message, so that callers can react to it without having to pull text apart. And keep the class small, because an exception that carries data and nothing else is easy to test and easy to document.