core: Show JSON error offsets where possible (#7437)

This commit is contained in:
Francis Lavoie
2026-01-14 22:54:19 -05:00
committed by GitHub
parent e40bd019ff
commit d269405eab
4 changed files with 18 additions and 4 deletions

View File

@@ -1110,7 +1110,10 @@ func unsyncedConfigAccess(method, path string, body []byte, out io.Writer) error
if len(body) > 0 {
err = json.Unmarshal(body, &val)
if err != nil {
return fmt.Errorf("decoding request body: %v", err)
if jsonErr, ok := err.(*json.SyntaxError); ok {
return fmt.Errorf("decoding request body: %w, at offset %d", jsonErr, jsonErr.Offset)
}
return fmt.Errorf("decoding request body: %w", err)
}
}

View File

@@ -81,7 +81,11 @@ func JSONModuleObject(val any, fieldName, fieldVal string, warnings *[]Warning)
err = json.Unmarshal(enc, &tmp)
if err != nil {
if warnings != nil {
*warnings = append(*warnings, Warning{Message: err.Error()})
message := err.Error()
if jsonErr, ok := err.(*json.SyntaxError); ok {
message = fmt.Sprintf("%v, at offset %d", jsonErr.Error(), jsonErr.Offset)
}
*warnings = append(*warnings, Warning{Message: message})
}
return nil
}

View File

@@ -231,7 +231,10 @@ func loadConfigWithLogger(logger *zap.Logger, configFile, adapterName string) ([
// validate that the config is at least valid JSON
err = json.Unmarshal(config, new(any))
if err != nil {
return nil, "", "", fmt.Errorf("config is not valid JSON: %v; did you mean to use a config adapter (the --adapter flag)?", err)
if jsonErr, ok := err.(*json.SyntaxError); ok {
return nil, "", "", fmt.Errorf("config is not valid JSON: %w, at offset %d; did you mean to use a config adapter (the --adapter flag)?", err, jsonErr.Offset)
}
return nil, "", "", fmt.Errorf("config is not valid JSON: %w; did you mean to use a config adapter (the --adapter flag)?", err)
}
}

View File

@@ -342,7 +342,11 @@ func ParseStructTag(tag string) (map[string]string, error) {
func StrictUnmarshalJSON(data []byte, v any) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
return dec.Decode(v)
err := dec.Decode(v)
if jsonErr, ok := err.(*json.SyntaxError); ok {
return fmt.Errorf("%w, at offset %d", jsonErr, jsonErr.Offset)
}
return err
}
var JSONRawMessageType = reflect.TypeFor[json.RawMessage]()