Skip to content

Commit

Permalink
add validation error for json middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertWHurst committed Jan 10, 2025
1 parent 2d106ee commit d43fe6d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 7 deletions.
16 changes: 13 additions & 3 deletions middleware/json/body-types.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,17 @@ package json
// defining JSON objects in a more concise manner.
type M map[string]any

// E is shorthand for Error. If you want to return a JSON wrapped error, you can
// If you want to return a JSON wrapped error, you can
// use this type. The JSON response will be {"error": "your error message"}.
// If the status is not set, it will default to 400.
type E string
// If the status is not set, it will default to 500.
type Error string

// A FieldError can be used as a response body to indicate that a request
// body failed validation. The response will be a JSON object with the field
// name as the key and the error message as the value.
// A slice of ValidatorErrors can also be used to return multiple validation
// errors.
type FieldError struct {
Field string
Error string
}
40 changes: 36 additions & 4 deletions middleware/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,51 @@ func marshalResponseBody(ctx *navaros.Context) {
if from != nil {
ctx.Headers.Add("Content-Type", "application/json")
}
switch str := from.(type) {
case E:

switch v := from.(type) {

case []FieldError:
if ctx.Status == 0 {
ctx.Status = 400
}
from = map[string]string{"error": string(str)}
from = M{
"error": "Validation error",
"fields": genFieldsField(v),
}

case FieldError:
if ctx.Status == 0 {
ctx.Status = 400
}
from = M{
"error": "Validation error",
"fields": genFieldsField([]FieldError{v}),
}

case Error:
if ctx.Status == 0 {
ctx.Status = 400
}
from = M{"error": string(v)}

case string:
from = map[string]string{"message": str}
from = M{"message": v}
}

jsonBytes, err := json.Marshal(from)
if err != nil {
return nil, err
}
return bytes.NewBuffer(jsonBytes), nil
})
}

func genFieldsField(errors []FieldError) []M {
var fields []M
for _, err := range errors {
field := M{}
field[err.Field] = err.Error
fields = append(fields, field)
}
return fields
}

0 comments on commit d43fe6d

Please sign in to comment.