From e09920e4f8298ce15ec745be07bdb4f7b8711aa2 Mon Sep 17 00:00:00 2001 From: Herbie Ong Date: Wed, 27 Feb 2019 13:37:06 -0800 Subject: [PATCH] internal/errors: fix New in eliding prefix Change-Id: I59c4c03f4115bfe6c4377924fadfd664245e878f Reviewed-on: https://go-review.googlesource.com/c/164277 Reviewed-by: Joe Tsai --- internal/errors/errors.go | 2 +- internal/errors/errors_test.go | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/internal/errors/errors.go b/internal/errors/errors.go index 4fddf39d..377d2ab1 100644 --- a/internal/errors/errors.go +++ b/internal/errors/errors.go @@ -116,7 +116,7 @@ func (invalidUTF8Error) InvalidUTF8() bool { return true } // returns an error that has a "proto" prefix. func New(f string, x ...interface{}) error { for i := 0; i < len(x); i++ { - if e, ok := x[i].(prefixError); ok { + if e, ok := x[i].(*prefixError); ok { x[i] = e.s // avoid "proto: " prefix when chaining } } diff --git a/internal/errors/errors_test.go b/internal/errors/errors_test.go index 8dd635ec..1d6464df 100644 --- a/internal/errors/errors_test.go +++ b/internal/errors/errors_test.go @@ -7,6 +7,7 @@ package errors import ( "errors" "reflect" + "strings" "testing" ) @@ -91,3 +92,24 @@ type customRequiredNotSetError struct{} func (customRequiredNotSetError) Error() string { return "required field not set" } func (customRequiredNotSetError) RequiredNotSet() bool { return true } + +func TestNewPrefix(t *testing.T) { + e1 := New("abc") + got := e1.Error() + if !strings.HasPrefix(got, "proto:") { + t.Errorf("missing \"proto:\" prefix in %q", got) + } + if !strings.Contains(got, "abc") { + t.Errorf("missing text \"abc\" in %q", got) + } + + e2 := New("%v", e1) + got = e2.Error() + if !strings.HasPrefix(got, "proto:") { + t.Errorf("missing \"proto:\" prefix in %q", got) + } + // Test to make sure prefix is removed from the embedded error. + if strings.Contains(strings.TrimPrefix(got, "proto:"), "proto:") { + t.Errorf("prefix \"proto:\" not elided in embedded error: %q", got) + } +}