fix(binding): preserve input indices in slice validation errors

This commit is contained in:
dazhou 2026-11-10 16:02:13 +08:00
parent 0f09c3a9b4
commit 3fe0d6e4b0
2 changed files with 44 additions and 1 deletions

View File

@ -5,6 +5,7 @@
package binding
import (
"errors"
"reflect"
"strconv"
"strings"
@ -20,6 +21,11 @@ type defaultValidator struct {
type SliceValidationError []error
type indexedValidationError struct {
error
index int
}
// Error concatenates all error elements in SliceValidationError into a single string separated by \n.
func (err SliceValidationError) Error() string {
if len(err) == 0 {
@ -29,11 +35,15 @@ func (err SliceValidationError) Error() string {
var b strings.Builder
for i := range len(err) {
if err[i] != nil {
index := i
if indexed, ok := errors.AsType[indexedValidationError](err[i]); ok {
index = indexed.index
}
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString("[")
b.WriteString(strconv.Itoa(i))
b.WriteString(strconv.Itoa(index))
b.WriteString("]: ")
b.WriteString(err[i].Error())
}
@ -41,6 +51,11 @@ func (err SliceValidationError) Error() string {
return b.String()
}
// Unwrap returns the original validation error.
func (err indexedValidationError) Unwrap() error {
return err.error
}
var _ StructValidator = (*defaultValidator)(nil)
// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
@ -63,6 +78,9 @@ func (v *defaultValidator) ValidateStruct(obj any) error {
validateRet := make(SliceValidationError, 0)
for i := range count {
if err := v.ValidateStruct(value.Index(i).Interface()); err != nil {
if i != len(validateRet) {
err = indexedValidationError{error: err, index: i}
}
validateRet = append(validateRet, err)
}
}

View File

@ -7,12 +7,14 @@ package binding
import (
"io"
"net/http/httptest"
"strings"
"testing"
"time"
"unsafe"
"github.com/gin-gonic/gin/codec/json"
"github.com/gin-gonic/gin/render"
"github.com/go-playground/validator/v10"
jsoniter "github.com/json-iterator/go"
"github.com/modern-go/reflect2"
"github.com/stretchr/testify/assert"
@ -37,6 +39,29 @@ func TestJSONBindingBindBodyMap(t *testing.T) {
assert.Equal(t, "world", s["hello"])
}
func TestJSONBindingBindBodySliceValidationIndex(t *testing.T) {
type item struct {
Name string `json:"name" binding:"required"`
}
var items []item
err := jsonBinding{}.BindBody([]byte(`[{},{"name":"valid"},{}]`), &items)
var failures SliceValidationError
require.ErrorAs(t, err, &failures)
require.Len(t, failures, 2)
lines := strings.Split(err.Error(), "\n")
require.Len(t, lines, 2)
assert.True(t, strings.HasPrefix(lines[0], "[0]:"), "error = %q", lines[0])
assert.True(t, strings.HasPrefix(lines[1], "[2]:"), "error = %q", lines[1])
var fields validator.ValidationErrors
require.ErrorAs(t, failures[1], &fields)
require.Len(t, fields, 1)
assert.Equal(t, "Name", fields[0].Field())
}
func TestCustomJsonCodec(t *testing.T) {
// Restore json encoding configuration after testing
oldMarshal := json.API