errors.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Package handlers
  2. package handlers
  3. import (
  4. "encoding/json"
  5. "log/slog"
  6. "net/http"
  7. )
  8. // AppEnv is set at startup to control error detail exposure
  9. var AppEnv string
  10. // writeJSON writes a JSON response
  11. func writeJSON(w http.ResponseWriter, status int, v interface{}) {
  12. w.Header().Set("Content-Type", "application/json")
  13. w.WriteHeader(status)
  14. json.NewEncoder(w).Encode(v)
  15. }
  16. // writeError writes an error response.
  17. // In production, internal server errors return a generic message.
  18. // In development, the actual error message is returned.
  19. func writeError(w http.ResponseWriter, status int, msg string, err error) {
  20. if err != nil {
  21. slog.Error("handler error", "status", status, "error", err)
  22. }
  23. if status == http.StatusInternalServerError && AppEnv == "production" {
  24. msg = "internal server error"
  25. }
  26. writeJSON(w, status, map[string]string{"error": msg})
  27. }
  28. // writeValidationError writes a validation error response (422)
  29. func writeValidationError(w http.ResponseWriter, err error) {
  30. writeJSON(w, http.StatusUnprocessableEntity, map[string]interface{}{
  31. "error": "validation failed",
  32. "details": err.Error(),
  33. })
  34. }