error.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package validate
  2. import "fmt"
  3. // Validation error.
  4. var (
  5. Err = Error{}
  6. )
  7. // Error represents a validation error.
  8. type Error struct {
  9. Message string
  10. Data []any
  11. }
  12. // Error retrieves the message of a validation Error.
  13. // If it has Data, the message will be formatted.
  14. func (e Error) Error() string {
  15. if len(e.Data) > 0 {
  16. return fmt.Sprintf(e.Message, e.Data...)
  17. }
  18. return e.Message
  19. }
  20. // Is determines whether the Error is an instance of the target.
  21. // https://pkg.go.dev/errors#Is
  22. //
  23. // If the target is a validation error and specifies a message, this function returns true if the messages match.
  24. // If the target is an empty validation error, this function always returns true.
  25. func (e Error) Is(target error) bool {
  26. if t, ok := target.(Error); ok {
  27. return t.Message == e.Message || t.Message == ""
  28. }
  29. return false
  30. }
  31. func (e Error) With(value any) Error {
  32. if e.Data == nil {
  33. e.Data = []any{}
  34. }
  35. e.Data = append(e.Data, value)
  36. return e
  37. }
  38. // NewError creates a new validation error.
  39. func NewError(message string) Error {
  40. return Error{
  41. Message: message,
  42. }
  43. }