Improve error message for nil values in repeated fields.
Also unexport ErrRepeatedHasNil, since there's no utility in checking for it.
diff --git a/proto/all_test.go b/proto/all_test.go
index 3fade17..aa67b10 100644
--- a/proto/all_test.go
+++ b/proto/all_test.go
@@ -1252,7 +1252,8 @@
}
o := old()
- if err := o.Marshal(pb); err != ErrRepeatedHasNil {
+ err := o.Marshal(pb)
+ if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") {
t.Fatalf("unexpected or no error when marshaling: %v", err)
}
}
diff --git a/proto/encode.go b/proto/encode.go
index 1512d60..cd826e9 100644
--- a/proto/encode.go
+++ b/proto/encode.go
@@ -60,9 +60,9 @@
}
var (
- // ErrRepeatedHasNil is the error returned if Marshal is called with
+ // errRepeatedHasNil is the error returned if Marshal is called with
// a struct with a repeated field containing a nil element.
- ErrRepeatedHasNil = errors.New("proto: repeated field has nil element")
+ errRepeatedHasNil = errors.New("proto: repeated field has nil element")
// ErrNil is the error returned if Marshal is called with nil.
ErrNil = errors.New("proto: Marshal called with nil")
@@ -939,7 +939,7 @@
for i := 0; i < l; i++ {
structp := s.Index(i)
if structPointer_IsNil(structp) {
- return ErrRepeatedHasNil
+ return errRepeatedHasNil
}
// Can the object marshal itself?
@@ -958,7 +958,7 @@
err := o.enc_len_struct(p.sprop, structp, &state)
if err != nil && !state.shouldContinue(err, nil) {
if err == ErrNil {
- return ErrRepeatedHasNil
+ return errRepeatedHasNil
}
return err
}
@@ -1001,7 +1001,7 @@
for i := 0; i < l; i++ {
b := s.Index(i)
if structPointer_IsNil(b) {
- return ErrRepeatedHasNil
+ return errRepeatedHasNil
}
o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
@@ -1010,7 +1010,7 @@
if err != nil && !state.shouldContinue(err, nil) {
if err == ErrNil {
- return ErrRepeatedHasNil
+ return errRepeatedHasNil
}
return err
}
@@ -1184,6 +1184,9 @@
if p.Required && state.err == nil {
state.err = &RequiredNotSetError{p.Name}
}
+ } else if err == errRepeatedHasNil {
+ // Give more context to nil values in repeated fields.
+ return errors.New("repeated field " + p.OrigName + " has nil element")
} else if !state.shouldContinue(err, p) {
return err
}