errdefs: centralize error handling
Now that we have most of the services required for use with containerd, it was found that common patterns were used throughout services. By defining a central `errdefs` package, we ensure that services will map errors to and from grpc consistently and cleanly. One can decorate an error with as much context as necessary, using `pkg/errors` and still have the error mapped correctly via grpc. We make a few sacrifices. At this point, the common errors we use across the repository all map directly to grpc error codes. While this seems positively crazy, it actually works out quite well. The error conditions that were specific weren't super necessary and the ones that were necessary now simply have better context information. We lose the ability to add new codes, but this constraint may not be a bad thing. Effectively, as long as one uses the errors defined in `errdefs`, the error class will be mapped correctly across the grpc boundary and everything will be good. If you don't use those definitions, the error maps to "unknown" and the error message is preserved. Signed-off-by: Stephen J Day <stephen.day@docker.com>
This commit is contained in:
@@ -3,6 +3,7 @@ package namespaces
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/containerd/containerd/errdefs"
|
||||
"github.com/containerd/containerd/identifiers"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/net/context"
|
||||
@@ -13,10 +14,6 @@ const (
|
||||
Default = "default"
|
||||
)
|
||||
|
||||
var (
|
||||
errNamespaceRequired = errors.New("namespace is required")
|
||||
)
|
||||
|
||||
type namespaceKey struct{}
|
||||
|
||||
// WithNamespace sets a given namespace on the context
|
||||
@@ -50,16 +47,11 @@ func Namespace(ctx context.Context) (string, bool) {
|
||||
return namespace, ok
|
||||
}
|
||||
|
||||
// IsNamespaceRequired returns whether an error is caused by a missing namespace
|
||||
func IsNamespaceRequired(err error) bool {
|
||||
return errors.Cause(err) == errNamespaceRequired
|
||||
}
|
||||
|
||||
// NamespaceRequired returns the valid namepace from the context or an error.
|
||||
func NamespaceRequired(ctx context.Context) (string, error) {
|
||||
namespace, ok := Namespace(ctx)
|
||||
if !ok || namespace == "" {
|
||||
return "", errNamespaceRequired
|
||||
return "", errors.Wrapf(errdefs.ErrFailedPrecondition, "namespace is required")
|
||||
}
|
||||
|
||||
if err := identifiers.Validate(namespace); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user