Files
budget-backend/internal/storage/validators/error.go
kratisto f81c902ca6
Some checks failed
golangci-lint / lint (push) Successful in 1m33s
Test / test (push) Failing after 2m16s
chore: migrate to gitea
2026-01-27 01:56:53 +01:00

46 lines
1.4 KiB
Go
Executable File

package validators
import (
"fmt"
"regexp"
"strings"
"gitea.frenchtouch.duckdns.org/kratisto/budget-backend/internal/storage/model"
"gitea.frenchtouch.duckdns.org/kratisto/budget-backend/internal/utils"
"gopkg.in/go-playground/validator.v9"
)
var regexpValidatorNamespacePrefix = regexp.MustCompile(`^\w+\.`)
func NewDataValidationAPIError(err error) model.APIError {
apiErr := model.ErrDataValidation
if err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
utils.GetLogger().WithError(err).WithField("templateAPIErr", apiErr).Error("InvalidValidationError")
} else {
for _, e := range err.(validator.ValidationErrors) {
reason := e.Tag()
if _, ok := CustomValidators[e.Tag()]; ok {
reason = truncatingSprintf(CustomValidators[e.Tag()].Message, e.Param())
}
namespaceWithoutStructName := regexpValidatorNamespacePrefix.ReplaceAllString(e.Namespace(), "")
fe := model.FieldError{
Field: namespaceWithoutStructName,
Constraint: e.Tag(),
Description: reason,
}
apiErr.Details = append(apiErr.Details, fe)
}
}
}
return apiErr
}
// truncatingSprintf is used as fmt.Sprintf but allow to truncate the additional parameters given when there is more parameters than %v in str
func truncatingSprintf(str string, args ...interface{}) string {
n := strings.Count(str, "%v")
return fmt.Sprintf(str, args[:n]...)
}