{"record":{"id":"35189b75fb1b8bfd","repo":"geektutu/7days-golang","slug":"err-error-35189b","errorCode":null,"errorMessage":"err.Error()","messagePattern":"err\\.Error\\(\\)","errorType":"http","errorClass":null,"httpStatus":500,"severity":"error","filePath":"gee-web/day4-group/gee/context.go","lineNumber":65,"sourceCode":"\tc.Writer.WriteHeader(code)\n}\n\nfunc (c *Context) SetHeader(key string, value string) {\n\tc.Writer.Header().Set(key, value)\n}\n\nfunc (c *Context) String(code int, format string, values ...interface{}) {\n\tc.SetHeader(\"Content-Type\", \"text/plain\")\n\tc.Status(code)\n\tc.Writer.Write([]byte(fmt.Sprintf(format, values...)))\n}\n\nfunc (c *Context) JSON(code int, obj interface{}) {\n\tc.SetHeader(\"Content-Type\", \"application/json\")\n\tc.Status(code)\n\tencoder := json.NewEncoder(c.Writer)\n\tif err := encoder.Encode(obj); err != nil {\n\t\thttp.Error(c.Writer, err.Error(), 500)\n\t}\n}\n\nfunc (c *Context) Data(code int, data []byte) {\n\tc.Status(code)\n\tc.Writer.Write(data)\n}\n\nfunc (c *Context) HTML(code int, html string) {\n\tc.SetHeader(\"Content-Type\", \"text/html\")\n\tc.Status(code)\n\tc.Writer.Write([]byte(html))\n}\n","sourceCodeStart":47,"sourceCodeEnd":79,"githubUrl":"https://github.com/geektutu/7days-golang/blob/cf3644382101dc13e7fd92e8f5c66cabc51bcd3b/gee-web/day4-group/gee/context.go#L47-L79","documentation":"This error surfaces inside Context.JSON when encoding.Engine.Encode fails to serialize the response object to JSON. The gee framework's JSON helper writes the object to the http.ResponseWriter; if the object contains values Go's encoding/json cannot marshal (e.g. channels, funcs, cyclic structures) or if the write fails mid-stream, Encode returns an error. The handler then writes the raw error message to the response with HTTP 500 via http.Error.","triggerScenarios":"Calling c.JSON(code, obj) where obj contains unsupported types (channel, func, complex), has a cyclic reference causing a json.UnsupportedTypeError/json.MarshalerError, or where the client has disconnected so the underlying Write to c.Writer fails.","commonSituations":"Returning structs with unexported-only fields plus invalid data, accidentally passing a channel or function value, embedding a cyclic pointer graph (e.g. parent/child linked nodes), or returning very large responses to clients that timed out and closed the connection.","solutions":["Fix the payload: ensure the object passed to c.JSON contains only JSON-serializable types (no channels, funcs, complex numbers, or cycles).","Add json:\"field\" tags and export fields on structs so marshaling produces expected output.","Implement json.Marshaler or pre-validate with json.Marshal(obj) in development/tests to catch unsupported types before writing headers.","Check whether the client disconnected (broken pipe); in that case log the error server-side rather than treating it as a payload bug.","Centralize the error: replace http.Error(500) with the framework's Fail/Abort helper so headers are set consistently."],"exampleFix":"// before\nc.JSON(http.StatusOK, map[string]interface{}{\n    \"conn\": someNetConn, // json: unsupported type\n})\n// after\nc.JSON(http.StatusOK, map[string]interface{}{\n    \"conn\": someNetConn.RemoteAddr().String(),\n})","handlingStrategy":"validation","validationCode":"func canMarshal(obj interface{}) error {\n    _, err := json.Marshal(obj)\n    return err\n}\n// call before responding:\nif err := canMarshal(payload); err != nil {\n    log.Printf(\"payload not JSON-serializable: %v\", err)\n    return\n}","typeGuard":"func isJSONSafe(v interface{}) bool {\n    switch v.(type) {\n    case chan struct{}, chan int, func(), complex64, complex128:\n        return false\n    }\n    return true\n}","tryCatchPattern":"// Go has no try/catch; handle the returned error explicitly\nif err := encoder.Encode(obj); err != nil {\n    if errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET) {\n        log.Printf(\"client disconnected: %v\", err)\n    } else {\n        log.Printf(\"json encode failed: %v\", err)\n        http.Error(c.Writer, \"internal server error\", 500)\n    }\n}","preventionTips":["Never put channels, funcs, or complex numbers in response structs; use a DTO layer for responses.","Keep response structs exported with explicit json tags.","Write unit tests that json.Marshal every handler response shape.","Watch logs for 'broken pipe'/'connection reset by peer' — those indicate client disconnects, not payload bugs.","Consider middleware that recovers and logs encode failures with the failing route for debugging."],"tags":["go","json","serialization","http"],"backgroundTag":"json-serialization-failed","analyzedSha":"cf3644382101dc13e7fd92e8f5c66cabc51bcd3b","analyzedAt":"2026-09-03T18:31:24.087Z","contentChangedAt":"2026-09-03T18:31:24.087Z","schemaVersion":2},"datasetVersion":"2026-09-08T05:18:18.240Z"}