Skip to content

Commit

Permalink
chore(validation): early return error
Browse files Browse the repository at this point in the history
  • Loading branch information
0iq authored Nov 23, 2024
1 parent 64a2a9d commit 6ac8a21
Showing 1 changed file with 31 additions and 30 deletions.
61 changes: 31 additions & 30 deletions validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,37 +37,38 @@ func validate(a any) error {
}

err := v.Struct(a)
if err != nil {
// this check is only needed when your code could produce an
// invalid value for validation such as interface with nil value
if _, exists := err.(*validator.InvalidValidationError); exists {
return fmt.Errorf("validation error: %w", err)
}
if err == nil {
return nil
}

// this check is only needed when your code could produce an
// invalid value for validation such as interface with nil value
if _, exists := err.(*validator.InvalidValidationError); exists {
return fmt.Errorf("validation error: %w", err)
}

validationError := HTTPError{
Err: err,
Status: http.StatusBadRequest,
Title: "Validation Error",
}
var errorsSummary []string
for _, err := range err.(validator.ValidationErrors) {
errorsSummary = append(errorsSummary, explainError(err))
validationError.Errors = append(validationError.Errors, ErrorItem{
Name: err.StructNamespace(),
Reason: err.Error(),
More: map[string]any{
"nsField": err.StructNamespace(),
"field": err.StructField(),
"tag": err.Tag(),
"param": err.Param(),
"value": err.Value(),
},
})
}
validationError := HTTPError{
Err: err,
Status: http.StatusBadRequest,
Title: "Validation Error",
}
var errorsSummary []string
for _, err := range err.(validator.ValidationErrors) {
errorsSummary = append(errorsSummary, explainError(err))
validationError.Errors = append(validationError.Errors, ErrorItem{
Name: err.StructNamespace(),
Reason: err.Error(),
More: map[string]any{
"nsField": err.StructNamespace(),
"field": err.StructField(),
"tag": err.Tag(),
"param": err.Param(),
"value": err.Value(),
},
})
}

validationError.Detail = strings.Join(errorsSummary, ", ")
validationError.Detail = strings.Join(errorsSummary, ", ")

return validationError
}
return nil
return validationError
}

0 comments on commit 6ac8a21

Please sign in to comment.