{"record":{"id":"a7fce6f98f3ca79f","repo":"gofr-dev/gofr","slug":"failed-to-marshal-value-to-json-w","errorCode":null,"errorMessage":"failed to marshal value to JSON: %w","messagePattern":"failed to marshal value to JSON: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"pkg/gofr/datasource/kv-store/dynamodb/dynamo.go","lineNumber":126,"sourceCode":"// UseMetrics sets the metrics for the Dynamo client which asserts the Metrics interface.\nfunc (c *Client) UseMetrics(metrics any) {\n\tif m, ok := metrics.(Metrics); ok {\n\t\tc.metrics = m\n\t}\n}\n\n// UseTracer sets the tracer for Dynamo client.\nfunc (c *Client) UseTracer(tracer any) {\n\tif tracer, ok := tracer.(trace.Tracer); ok {\n\t\tc.tracer = tracer\n\t}\n}\n\n// ToJSON converts a Go struct to JSON string for use with KVStore.Set.\nfunc ToJSON(value any) (string, error) {\n\tjsonData, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal value to JSON: %w\", err)\n\t}\n\n\treturn string(jsonData), nil\n}\n\n// FromJSON converts a JSON string to a Go struct for use with KVStore.Get.\nfunc FromJSON(jsonData string, dest any) error {\n\tif err := json.Unmarshal([]byte(jsonData), dest); err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal JSON: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (c *Client) Get(ctx context.Context, key string) (string, error) {\n\tif !c.connected {\n\t\treturn \"\", errClientNotConnected\n\t}","sourceCodeStart":108,"sourceCodeEnd":144,"githubUrl":"https://github.com/gofr-dev/gofr/blob/187eb24962502e91f1fee856230670958b66e89c/pkg/gofr/datasource/kv-store/dynamodb/dynamo.go#L108-L144","documentation":"ToJSON marshals a Go value to a JSON string for use with KVStore.Set. This error wraps json.Marshal failures with 'failed to marshal value to JSON: %w' when the value contains types JSON cannot represent.","triggerScenarios":"Calling ToJSON with a struct containing channels, functions, complex numbers, or NaN/Inf floats; passing a value with unmarshalable custom MarshalJSON that errors; cyclic data handled by marshal returning an error.","commonSituations":"Passing structs with func or chan fields (e.g. logger, connection handles) straight to Set, NaN from float math, time.Time in unusual layouts is fine but custom marshalers returning errors are not.","solutions":["Remove or tag unmarshalable fields (chan, func) with json:\"-\" so the marshaler skips them","Convert NaN/Inf floats to valid numbers or omit them before calling ToJSON","Call ToJSON first and log the wrapped %w cause to identify the offending field","Pre-serialize in tests (Test_ToJSONError pattern) to catch bad shapes early"],"exampleFix":"// before\ntype Session struct { Done chan struct{} }\ns, _ := ToJSON(Session{}) // error\n// after\ntype Session struct { Done chan struct{} `json:\"-\"` }\ns, err := ToJSON(Session{})","handlingStrategy":"validation","validationCode":"func jsonSafe(v any) error {\n    rv := reflect.ValueOf(v)\n    for rv.Kind() == reflect.Ptr { rv = rv.Elem() }\n    if rv.Kind() == reflect.Struct {\n        for i := 0; i < rv.NumField(); i++ {\n            switch rv.Field(i).Kind() {\n            case reflect.Chan, reflect.Func, reflect.Complex64, reflect.Complex128:\n                return fmt.Errorf(\"field %s not JSON-serializable\", rv.Type().Field(i).Name)\n            }\n        }\n    }\n    return nil\n}","typeGuard":"func isMarshalable(v any) bool { _, err := json.Marshal(v); return err == nil }","tryCatchPattern":"s, err := dynamodb.ToJSON(value)\nif err != nil {\n    var ue *json.UnsupportedTypeError\n    if errors.As(err, &ue) { log.Printf(\"unsupported type: %v\", ue.Value); return nil, err }\n    return nil, err\n}","preventionTips":["Keep chan/func fields out of stored structs or tag them json:\"-\"","Sanitize NaN/Inf floats before storing","Write a unit test that round-trips every stored struct via ToJSON/FromJSON","Log the wrapped %w cause to pinpoint the offending field"],"tags":["json","serialization","dynamodb","kv-store"],"backgroundTag":"json-marshaling-failed","analyzedSha":"187eb24962502e91f1fee856230670958b66e89c","analyzedAt":"2026-09-01T20:34:54.554Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}