|
1 | 1 | package fiberoapi |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "encoding/json" |
5 | | - "errors" |
6 | 4 | "fmt" |
7 | 5 | "reflect" |
8 | 6 | "strconv" |
@@ -52,12 +50,33 @@ func parseInput[TInput any](app *OApiApp, c *fiber.Ctx, path string, options *Op |
52 | 50 | // It's OK, the POST has no body - ignore the error |
53 | 51 | } else { |
54 | 52 | // 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 | + } |
60 | 78 | } |
| 79 | + |
61 | 80 | return input, err |
62 | 81 | } |
63 | 82 | } |
|
0 commit comments