Skip to content

Commit

Permalink
Add Error method to laravel like error and add prefix method to Valid…
Browse files Browse the repository at this point in the history
…ationError

Once the error has been converted to a laravel like error you can now
also return it as a go error.

The Prefix method is handy if you execute validation somewhere nested in
your codebase and want to prefix all validation error paths higher up in the
codebase.
  • Loading branch information
mjarkk committed Nov 18, 2024
1 parent 127a6b2 commit 64af40b
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ func (v *ValidationError) Error() string {
return fallbackErrorMessage
}

func (v *LaravelValidationError) Error() string {
for _, entry := range v.Errors {
for _, message := range entry.Value {
return message
}
}

return fallbackErrorMessage
}

type FieldErrors struct {
Path string `json:"path"`
Errors []FieldValidatorError `json:"errors"`
Expand Down Expand Up @@ -67,6 +77,7 @@ func (obj LaravelErrorObj) MarshalJSON() ([]byte, error) {
return resp, nil
}

// ToLaravelError converts a ValidationError to Laravel like validation error
func (e *ValidationError) ToLaravelError() *LaravelValidationError {
errors := LaravelErrorObj{}

Expand All @@ -88,3 +99,11 @@ func (e *ValidationError) ToLaravelError() *LaravelValidationError {
Message: "Form contains errors",
}
}

// Prefix prefixes all paths in the error with the given prefix
func (e *ValidationError) Prefix(prefix string) {
for idx, fieldError := range e.Errors {
fieldError.Path = prefix + fieldError.Path
e.Errors[idx] = fieldError
}
}

0 comments on commit 64af40b

Please sign in to comment.