diff --git a/docs/features/errors.md b/docs/features/errors.md index adb6f69..d739047 100644 --- a/docs/features/errors.md +++ b/docs/features/errors.md @@ -185,4 +185,6 @@ v := valigo.New(valigo.WithErrorsTransformer(func(errs []shared.Error) []error { })) ``` +`shared.Errors` is a `[]shared.Error` as one error, its `Error()` joins the errors by `; `; the adapters of the frameworks return it, get it back by `errors.As(err, &errs)`. + The transformer is called only when there are errors. For an HTTP API the [`problem`](problem.md) package has the transformer of the problem details of RFC 9457. diff --git a/shared/error.go b/shared/error.go index 9fb1f21..510b51a 100644 --- a/shared/error.go +++ b/shared/error.go @@ -1,6 +1,9 @@ package shared -import "fmt" +import ( + "fmt" + "strings" +) // Error define a custom error struct. type Error struct { @@ -23,3 +26,19 @@ func (e Error) Error() string { } return fmt.Sprintf("%s (%s: %v)", e.Message, e.Location, e.Value) } + +// Errors is the errors of a validation as one error, e.g. for the validator interfaces of the frameworks. +// Get it back from an error by errors.As(err, &errs). +type Errors []Error + +// Error returns the errors joined by "; ". +func (e Errors) Error() string { + var b strings.Builder + for i, err := range e { + if i > 0 { + b.WriteString("; ") + } + b.WriteString(err.Error()) + } + return b.String() +} diff --git a/shared/error_test.go b/shared/error_test.go index 85fe929..edb534b 100644 --- a/shared/error_test.go +++ b/shared/error_test.go @@ -1,6 +1,8 @@ package shared import ( + "errors" + "fmt" "testing" ) @@ -58,3 +60,17 @@ func TestError(t *testing.T) { }) } } + +func TestErrors(t *testing.T) { + errs := Errors{{Message: "a", Location: "x", Value: 1}, {Message: "b"}} + if got := errs.Error(); got != "a (x: 1); b" { + t.Errorf("Error() = %q", got) + } + var target Errors + if !errors.As(fmt.Errorf("wrapped: %w", errs), &target) || len(target) != 2 { + t.Errorf("errors.As failed: %v", target) + } + if got := Errors(nil).Error(); got != "" { + t.Errorf("Error() of no errors = %q", got) + } +}