Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/features/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
21 changes: 20 additions & 1 deletion shared/error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package shared

import "fmt"
import (
"fmt"
"strings"
)

// Error define a custom error struct.
type Error struct {
Expand All @@ -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()
}
16 changes: 16 additions & 0 deletions shared/error_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package shared

import (
"errors"
"fmt"
"testing"
)

Expand Down Expand Up @@ -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)
}
}
Loading