context: produce a nicer panic message for a nil WithValue key

Change-Id: I2e8ae403622ba7131cadaba506100d79613183f1
Reviewed-on: https://go-review.googlesource.com/22601
Reviewed-by: Russ Cox <rsc@golang.org>
Reviewed-by: Andrew Gerrand <adg@golang.org>
This commit is contained in:
Brad Fitzpatrick 2016-04-28 22:04:30 -05:00
parent 694846a548
commit c884f6594a
2 changed files with 7 additions and 0 deletions

View File

@ -428,6 +428,9 @@ func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
//
// The provided key must be comparable.
func WithValue(parent Context, key, val interface{}) Context {
if key == nil {
panic("nil key")
}
if !reflect.TypeOf(key).Comparable() {
panic("key is not comparable")
}

View File

@ -583,6 +583,10 @@ func TestWithValueChecksKey(t *testing.T) {
if panicVal == nil {
t.Error("expected panic")
}
panicVal = recoveredValue(func() { WithValue(Background(), nil, "bar") })
if got, want := fmt.Sprint(panicVal), "nil key"; got != want {
t.Errorf("panic = %q; want %q", got, want)
}
}
func recoveredValue(fn func()) (v interface{}) {