Published on

Go API Errors: Friendly JSON Responses

Authors
  • Mehdi Akiki avatar
    Name
    Mehdi Akiki
    Twitter

Good errors save time.

Code (short)

func writeErr(w http.ResponseWriter, code int, msg string) {
  w.Header().Set("Content-Type", "application/json")
  w.WriteHeader(code)
  json.NewEncoder(w).Encode(map[string]any{"error": msg})
}

Tips

  • Use standard codes (400, 401, 404, 500)
  • Include a trace id if you have one
  • Keep messages simple

I build and scale reliable production systems. Open to full-time and freelance work with U.S.-based teams that value ownership and execution.

Got something in mind?

Book a Discovery Call