errorhandler.go 1005 B

12345678910111213141516171819202122232425262728293031323334
  1. package server
  2. import (
  3. "net/http"
  4. "github.com/docker/docker/api/server/httpstatus"
  5. "github.com/docker/docker/api/server/httputils"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/api/types/versions"
  8. "github.com/gorilla/mux"
  9. "google.golang.org/grpc/status"
  10. )
  11. // makeErrorHandler makes an HTTP handler that decodes a Docker error and
  12. // returns it in the response.
  13. func makeErrorHandler(err error) http.HandlerFunc {
  14. return func(w http.ResponseWriter, r *http.Request) {
  15. statusCode := httpstatus.FromError(err)
  16. vars := mux.Vars(r)
  17. if apiVersionSupportsJSONErrors(vars["version"]) {
  18. response := &types.ErrorResponse{
  19. Message: err.Error(),
  20. }
  21. _ = httputils.WriteJSON(w, statusCode, response)
  22. } else {
  23. http.Error(w, status.Convert(err).Message(), statusCode)
  24. }
  25. }
  26. }
  27. func apiVersionSupportsJSONErrors(version string) bool {
  28. const firstAPIVersionWithJSONErrors = "1.23"
  29. return version == "" || versions.GreaterThan(version, firstAPIVersionWithJSONErrors)
  30. }