Skip to content

Commit

Permalink
Make ErrBadName checkable via errors.Is() (#1462)
Browse files Browse the repository at this point in the history
* Make ErrBadName checkable via errors.Is()

The function IsErrBadName says it is deprecated and directs the user to
use errors.Is(), but that will never return true because this error is
custom based on the tag value.

This fixes that problem by implementing an Is() function on ErrBadName
so that errors.Is() can properly identify the error as an ErrBadName.
Usage can now be: errors.Is(err, &ErrBadName{})

Signed-off-by: Craig Jellick <craig@acorn.io>

* Update pkg/name/errors_test.go

Co-authored-by: Jason Hall <jason@chainguard.dev>

Signed-off-by: Craig Jellick <craig@acorn.io>
Co-authored-by: Jason Hall <jason@chainguard.dev>
  • Loading branch information
cjellick and imjasonh committed Oct 14, 2022
1 parent 7268da0 commit a0f6687
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pkg/name/errors.go
Expand Up @@ -28,6 +28,12 @@ func (e *ErrBadName) Error() string {
return e.info
}

// Is reports whether target is an error of type ErrBadName
func (e *ErrBadName) Is(target error) bool {
var berr *ErrBadName
return errors.As(target, &berr)
}

// newErrBadName returns a ErrBadName which returns the given formatted string from Error().
func newErrBadName(fmtStr string, args ...interface{}) *ErrBadName {
return &ErrBadName{fmt.Sprintf(fmtStr, args...)}
Expand Down
3 changes: 3 additions & 0 deletions pkg/name/errors_test.go
Expand Up @@ -31,4 +31,7 @@ func TestBadName(t *testing.T) {
if err.Error() != "could not parse reference: @@" {
t.Errorf("Unexpected string: %v", err)
}
if !errors.Is(err, &ErrBadName{}) {
t.Errorf("Not an ErrBadName using errors.Is: %v", err)
}
}

0 comments on commit a0f6687

Please sign in to comment.