api: keep the error contract JSON even on encoder failure

writeJSON's last-resort branch (json.Marshal failing, a programmer
error: unsupported type or cyclic data) previously fell back to
http.Error, which answers text/plain and was the one corner where the
API broke its own {"error": ...} contract. It now writes a
hand-written constant JSON literal: still strictly simpler than the
encoder that just failed (the reason writeError, which is built ON
writeJSON, cannot be used there: it would be circular), but contract
consistent. Tested by forcing the branch with a channel payload,
which json.Marshal cannot encode.
This commit is contained in:
Justin Visser 2026-06-10 16:22:35 +02:00
parent b49d92ec50
commit 2feb6ea5a3
2 changed files with 29 additions and 1 deletions

View file

@ -109,7 +109,12 @@ func handleScenario(w http.ResponseWriter, r *http.Request) {
func writeJSON(w http.ResponseWriter, status int, payload any) {
body, err := json.Marshal(payload)
if err != nil {
http.Error(w, "encoding response failed", http.StatusInternalServerError)
// Last-resort path: report the encoder's failure without using the
// encoder. The hand-written constant keeps the error contract JSON
// while staying strictly simpler than what just failed.
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":"encoding response failed"}`))
return
}
w.Header().Set("Content-Type", "application/json")