summaryrefslogtreecommitdiff
path: root/api/server/httputils
diff options
context:
space:
mode:
authorBrian Goff <cpuguy83@gmail.com>2017-07-19 10:20:13 -0400
committerBrian Goff <cpuguy83@gmail.com>2017-08-15 16:01:11 -0400
commitebcb7d6b406fe50ea9a237c73004d75884184c33 (patch)
treec87316ace5b2ddc5efabeb311d47e98fd4113ce9 /api/server/httputils
parentb6498340b2baa6596553b2b56b43990a365a7b6a (diff)
downloaddocker-ebcb7d6b406fe50ea9a237c73004d75884184c33.tar.gz
Remove string checking in API error handling
Use strongly typed errors to set HTTP status codes. Error interfaces are defined in the api/errors package and errors returned from controllers are checked against these interfaces. Errors can be wraeped in a pkg/errors.Causer, as long as somewhere in the line of causes one of the interfaces is implemented. The special error interfaces take precedence over Causer, meaning if both Causer and one of the new error interfaces are implemented, the Causer is not traversed. Signed-off-by: Brian Goff <cpuguy83@gmail.com>
Diffstat (limited to 'api/server/httputils')
-rw-r--r--api/server/httputils/errors.go78
-rw-r--r--api/server/httputils/form.go24
-rw-r--r--api/server/httputils/httputils.go20
3 files changed, 69 insertions, 53 deletions
diff --git a/api/server/httputils/errors.go b/api/server/httputils/errors.go
index b677f95d6a..10628f6b33 100644
--- a/api/server/httputils/errors.go
+++ b/api/server/httputils/errors.go
@@ -1,9 +1,10 @@
package httputils
import (
+ "fmt"
"net/http"
- "strings"
+ "github.com/docker/docker/api/errdefs"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/versions"
"github.com/gorilla/mux"
@@ -20,13 +21,8 @@ type httpStatusError interface {
HTTPErrorStatusCode() int
}
-// inputValidationError is an interface
-// that errors generated by invalid
-// inputs can implement to tell the
-// api layer to set a 400 status code
-// in the response.
-type inputValidationError interface {
- IsValidationError() bool
+type causer interface {
+ Cause() error
}
// GetHTTPErrorStatusCode retrieves status code from error message.
@@ -37,49 +33,44 @@ func GetHTTPErrorStatusCode(err error) int {
}
var statusCode int
- errMsg := err.Error()
- switch e := err.(type) {
- case httpStatusError:
- statusCode = e.HTTPErrorStatusCode()
- case inputValidationError:
+ // Stop right there
+ // Are you sure you should be adding a new error class here? Do one of the existing ones work?
+
+ // Note that the below functions are already checking the error causal chain for matches.
+ switch {
+ case errdefs.IsNotFound(err):
+ statusCode = http.StatusNotFound
+ case errdefs.IsInvalidParameter(err):
statusCode = http.StatusBadRequest
+ case errdefs.IsConflict(err):
+ statusCode = http.StatusConflict
+ case errdefs.IsUnauthorized(err):
+ statusCode = http.StatusUnauthorized
+ case errdefs.IsUnavailable(err):
+ statusCode = http.StatusServiceUnavailable
+ case errdefs.IsForbidden(err):
+ statusCode = http.StatusForbidden
+ case errdefs.IsNotModified(err):
+ statusCode = http.StatusNotModified
+ case errdefs.IsNotImplemented(err):
+ statusCode = http.StatusNotImplemented
+ case errdefs.IsSystem(err) || errdefs.IsUnknown(err):
+ statusCode = http.StatusInternalServerError
default:
statusCode = statusCodeFromGRPCError(err)
if statusCode != http.StatusInternalServerError {
return statusCode
}
- // FIXME: this is brittle and should not be necessary, but we still need to identify if
- // there are errors falling back into this logic.
- // If we need to differentiate between different possible error types,
- // we should create appropriate error types that implement the httpStatusError interface.
- errStr := strings.ToLower(errMsg)
-
- for _, status := range []struct {
- keyword string
- code int
- }{
- {"not found", http.StatusNotFound},
- {"cannot find", http.StatusNotFound},
- {"no such", http.StatusNotFound},
- {"bad parameter", http.StatusBadRequest},
- {"no command", http.StatusBadRequest},
- {"conflict", http.StatusConflict},
- {"impossible", http.StatusNotAcceptable},
- {"wrong login/password", http.StatusUnauthorized},
- {"unauthorized", http.StatusUnauthorized},
- {"hasn't been activated", http.StatusForbidden},
- {"this node", http.StatusServiceUnavailable},
- {"needs to be unlocked", http.StatusServiceUnavailable},
- {"certificates have expired", http.StatusServiceUnavailable},
- {"repository does not exist", http.StatusNotFound},
- } {
- if strings.Contains(errStr, status.keyword) {
- statusCode = status.code
- break
- }
+ if e, ok := err.(causer); ok {
+ return GetHTTPErrorStatusCode(e.Cause())
}
+
+ logrus.WithFields(logrus.Fields{
+ "module": "api",
+ "error_type": fmt.Sprintf("%T", err),
+ }).Debugf("FIXME: Got an API for which error does not match any expected type!!!: %+v", err)
}
if statusCode == 0 {
@@ -133,6 +124,9 @@ func statusCodeFromGRPCError(err error) int {
case codes.Unavailable: // code 14
return http.StatusServiceUnavailable
default:
+ if e, ok := err.(causer); ok {
+ return statusCodeFromGRPCError(e.Cause())
+ }
// codes.Canceled(1)
// codes.Unknown(2)
// codes.DeadlineExceeded(4)
diff --git a/api/server/httputils/form.go b/api/server/httputils/form.go
index 78bd379c7a..a5f62287ec 100644
--- a/api/server/httputils/form.go
+++ b/api/server/httputils/form.go
@@ -1,7 +1,6 @@
package httputils
import (
- "errors"
"net/http"
"path/filepath"
"strconv"
@@ -49,6 +48,16 @@ type ArchiveOptions struct {
Path string
}
+type badParameterError struct {
+ param string
+}
+
+func (e badParameterError) Error() string {
+ return "bad parameter: " + e.param + "cannot be empty"
+}
+
+func (e badParameterError) InvalidParameter() {}
+
// ArchiveFormValues parses form values and turns them into ArchiveOptions.
// It fails if the archive name and path are not in the request.
func ArchiveFormValues(r *http.Request, vars map[string]string) (ArchiveOptions, error) {
@@ -57,14 +66,13 @@ func ArchiveFormValues(r *http.Request, vars map[string]string) (ArchiveOptions,
}
name := vars["name"]
- path := filepath.FromSlash(r.Form.Get("path"))
-
- switch {
- case name == "":
- return ArchiveOptions{}, errors.New("bad parameter: 'name' cannot be empty")
- case path == "":
- return ArchiveOptions{}, errors.New("bad parameter: 'path' cannot be empty")
+ if name == "" {
+ return ArchiveOptions{}, badParameterError{"name"}
}
+ path := filepath.FromSlash(r.Form.Get("path"))
+ if path == "" {
+ return ArchiveOptions{}, badParameterError{"path"}
+ }
return ArchiveOptions{name, path}, nil
}
diff --git a/api/server/httputils/httputils.go b/api/server/httputils/httputils.go
index 4708d7d16e..57eeb4beba 100644
--- a/api/server/httputils/httputils.go
+++ b/api/server/httputils/httputils.go
@@ -1,12 +1,12 @@
package httputils
import (
- "fmt"
"io"
"mime"
"net/http"
"strings"
+ "github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
@@ -43,6 +43,20 @@ func CloseStreams(streams ...interface{}) {
}
}
+type validationError struct {
+ cause error
+}
+
+func (e validationError) Error() string {
+ return e.cause.Error()
+}
+
+func (e validationError) Cause() error {
+ return e.cause
+}
+
+func (e validationError) InvalidParameter() {}
+
// CheckForJSON makes sure that the request's Content-Type is application/json.
func CheckForJSON(r *http.Request) error {
ct := r.Header.Get("Content-Type")
@@ -58,7 +72,7 @@ func CheckForJSON(r *http.Request) error {
if matchesContentType(ct, "application/json") {
return nil
}
- return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
+ return validationError{errors.Errorf("Content-Type specified (%s) must be 'application/json'", ct)}
}
// ParseForm ensures the request form is parsed even with invalid content types.
@@ -68,7 +82,7 @@ func ParseForm(r *http.Request) error {
return nil
}
if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
- return err
+ return validationError{err}
}
return nil
}