Skip to content

Commit f0b3d14

Browse files
committed
errors: add an error for nonexistent objects
Depending on the storage backend used, we can return any of several errors if an object doesn't exist. For consistency, let's add an error specifically for this condition and place it into a new errors package so that it can be referred to from both the main package and the pack package without import cycles. Add a function in addition to quickly determine if the error is due to a missing object.
1 parent 686fe1b commit f0b3d14

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

errors/errors.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package errors
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
// noSuchObject is an error type that occurs when no object with a given object
8+
// ID is available.
9+
type noSuchObject struct {
10+
oid []byte
11+
}
12+
13+
// Error implements the error.Error() function.
14+
func (e *noSuchObject) Error() string {
15+
return fmt.Sprintf("gitobj: no such object: %x", e.oid)
16+
}
17+
18+
// NoSuchObject creates a new error representing a missing object with a given
19+
// object ID.
20+
func NoSuchObject(oid []byte) error {
21+
return &noSuchObject{oid: oid}
22+
}
23+
24+
// IsNoSuchObject indicates whether an error is a noSuchObject and is non-nil.
25+
func IsNoSuchObject(e error) bool {
26+
err, ok := e.(*noSuchObject)
27+
return ok && err != nil
28+
}

errors/errors_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package errors
2+
3+
import (
4+
"encoding/hex"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestNoSuchObjectTypeErrFormatting(t *testing.T) {
11+
sha := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12+
oid, err := hex.DecodeString(sha)
13+
assert.NoError(t, err)
14+
15+
err = NoSuchObject(oid)
16+
17+
assert.Equal(t, "gitobj: no such object: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", err.Error())
18+
assert.Equal(t, IsNoSuchObject(err), true)
19+
}
20+
21+
func TestIsNoSuchObjectNilHandling(t *testing.T) {
22+
assert.Equal(t, IsNoSuchObject((*noSuchObject)(nil)), false)
23+
assert.Equal(t, IsNoSuchObject(nil), false)
24+
}

0 commit comments

Comments
 (0)