This commit is contained in:
oneao committed 2025-11-05 22:25:09 +08:00
1 parent c7a1f83c67
commit 6849579652
19 files changed
+600 -249

No files matched your search

@@ -1,19 +1,34 @@
package errs
import "fmt"
import (
"fmt"
"strings"
)
// ValidationError 用于收集多个字段错误,同时实现 error 接口
type ValidationError struct {
field string
message string
Errors map[string]string // key: 字段名, value: 错误信息
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("字段 %s: %s", e.field, e.message)
// Error 实现 error 接口
func (v *ValidationError) Error() string {
if len(v.Errors) == 0 {
return ""
}
msgs := make([]string, 0, len(v.Errors))
for field, msg := range v.Errors {
msgs = append(msgs, fmt.Sprintf("%s: %s", field, msg))
}
return strings.Join(msgs, "; ")
}
func NewValidationError(field, message string) error {
// NewValidationError 创建多字段的 ValidationError
func NewValidationError(errors map[string]string) error {
if len(errors) == 0 {
return nil
}
return &ValidationError{
field: field,
message: message,
Errors: errors,
}
}