Skip to content

Commit 06d2a20

Browse files
authored
fix: Nested error handling support on JSONschema validation (#338)
There's an error and errors structure, need to handle both options
1 parent c457986 commit 06d2a20

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

internal/codegen/tpl_stencil_schema.go

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,16 +62,15 @@ func validateJSONSchema(identifier string, schemaMap map[string]any, data any) e
6262
for _, validationErr := range validationError.DetailedOutput().Errors {
6363
pth := strings.TrimPrefix(validationErr.InstanceLocation, "/")
6464

65-
//nolint:errcheck // Why: Best effort way to get the error.
66-
b, _ := validationErr.Error.MarshalJSON()
65+
errStrs := recurseError(&validationErr, []string{})
6766

68-
errStr := strings.TrimSuffix(strings.TrimPrefix(string(b), "\""), "\"")
67+
//nolint:errcheck // Why: Best effort way to get the error.
6968
if pth == "" {
7069
// Can't provide detailed field information. Wrapped error
7170
// will provide the top-level location.
72-
errs = append(errs, fmt.Errorf("%s", errStr))
71+
errs = append(errs, fmt.Errorf("%s", strings.Join(errStrs, ", ")))
7372
} else {
74-
errs = append(errs, fmt.Errorf("%s: %s", pth, errStr))
73+
errs = append(errs, fmt.Errorf("%s: %s", pth, strings.Join(errStrs, ", ")))
7574
}
7675
}
7776
} else {
@@ -83,3 +82,20 @@ func validateJSONSchema(identifier string, schemaMap map[string]any, data any) e
8382

8483
return nil
8584
}
85+
86+
// recurseError recursively traverses the output unit struct which has both singular and plural error fields,
87+
// returning a slice of error strings that it's adding onto.
88+
func recurseError(ou *jsonschema.OutputUnit, errStrs []string) []string {
89+
if ou.Error != nil {
90+
//nolint:errcheck // Why: Best effort way to get the error.
91+
b, _ := ou.Error.MarshalJSON()
92+
93+
errStr := strings.TrimSuffix(strings.TrimPrefix(string(b), "\""), "\"")
94+
errStrs = append(errStrs, errStr)
95+
} else if len(ou.Errors) > 0 {
96+
for _, ne := range ou.Errors {
97+
recurseError(&ne, errStrs)
98+
}
99+
}
100+
return errStrs
101+
}

0 commit comments

Comments
 (0)