Skip to content

Commit 11ed8d6

Browse files
committed
Enhance JSON unmarshal error handling to provide clearer validation messages
1 parent 868d736 commit 11ed8d6

1 file changed

Lines changed: 26 additions & 7 deletions

File tree

common.go

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
package fiberoapi
22

33
import (
4-
"encoding/json"
5-
"errors"
64
"fmt"
75
"reflect"
86
"strconv"
@@ -52,12 +50,33 @@ func parseInput[TInput any](app *OApiApp, c *fiber.Ctx, path string, options *Op
5250
// It's OK, the POST has no body - ignore the error
5351
} else {
5452
// Transform JSON unmarshal type errors into readable validation errors
55-
// Using errors.As for more robust error handling (handles wrapped errors)
56-
var unmarshalErr *json.UnmarshalTypeError
57-
if errors.As(err, &unmarshalErr) {
58-
return input, fmt.Errorf("invalid type for field '%s': expected %s but got %s",
59-
unmarshalErr.Field, unmarshalErr.Type.String(), unmarshalErr.Value)
53+
// Check if error message contains unmarshal type error pattern
54+
errMsg := err.Error()
55+
if strings.Contains(errMsg, "json: cannot unmarshal") && strings.Contains(errMsg, "into Go struct field") {
56+
// Parse the error message to extract field name and type info
57+
// Format: "json: cannot unmarshal <type> into Go struct field <StructName>.<Field> of type <GoType>"
58+
parts := strings.Split(errMsg, "into Go struct field ")
59+
if len(parts) == 2 {
60+
afterField := parts[1]
61+
fieldParts := strings.Split(afterField, " of type ")
62+
if len(fieldParts) == 2 {
63+
// Extract field name (after the last dot)
64+
fullFieldName := fieldParts[0]
65+
fieldNameParts := strings.Split(fullFieldName, ".")
66+
fieldName := fieldNameParts[len(fieldNameParts)-1]
67+
68+
// Extract expected type
69+
expectedType := fieldParts[1]
70+
71+
// Extract actual type from the first part
72+
typePart := strings.TrimPrefix(parts[0], "json: cannot unmarshal ")
73+
74+
return input, fmt.Errorf("invalid type for field '%s': expected %s but got %s",
75+
fieldName, expectedType, typePart)
76+
}
77+
}
6078
}
79+
6180
return input, err
6281
}
6382
}

0 commit comments

Comments
 (0)