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:
@@ -17,6 +17,7 @@ package identifiers
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/containerd/containerd/errdefs"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -32,15 +33,8 @@ var (
|
||||
// Rules for domains, defined in RFC 1035, section 2.3.1, are used for
|
||||
// identifiers.
|
||||
identifierRe = regexp.MustCompile(reAnchor(label + reGroup("[.]"+reGroup(label)) + "*"))
|
||||
|
||||
errIdentifierInvalid = errors.New("invalid identifier")
|
||||
)
|
||||
|
||||
// IsInvalid return true if the error was due to an invalid identifer.
|
||||
func IsInvalid(err error) bool {
|
||||
return errors.Cause(err) == errIdentifierInvalid
|
||||
}
|
||||
|
||||
// Validate return nil if the string s is a valid identifier.
|
||||
//
|
||||
// identifiers must be valid domain identifiers according to RFC 1035, section 2.3.1. To
|
||||
@@ -50,11 +44,11 @@ func IsInvalid(err error) bool {
|
||||
// a domain identifier or filesystem path component.
|
||||
func Validate(s string) error {
|
||||
if len(s) > maxLength {
|
||||
return errors.Wrapf(errIdentifierInvalid, "identifier %q greater than maximum length (%d characters)", s, maxLength)
|
||||
return errors.Wrapf(errdefs.ErrInvalidArgument, "identifier %q greater than maximum length (%d characters)", s, maxLength)
|
||||
}
|
||||
|
||||
if !identifierRe.MatchString(s) {
|
||||
return errors.Wrapf(errIdentifierInvalid, "identifier %q must match %v", s, identifierRe)
|
||||
return errors.Wrapf(errdefs.ErrInvalidArgument, "identifier %q must match %v", s, identifierRe)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user