]> Cypherpunks repositories - gostls13.git/commitdiff
context: produce a nicer panic message for a nil WithValue key
authorBrad Fitzpatrick <bradfitz@golang.org>
Fri, 29 Apr 2016 03:04:30 +0000 (22:04 -0500)
committerBrad Fitzpatrick <bradfitz@golang.org>
Fri, 29 Apr 2016 03:20:51 +0000 (03:20 +0000)
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>
src/context/context.go
src/context/context_test.go

index da294b12921bc041162d6496c81b71b7f2e641de..5184b94e514c18b2225621bfe75f95148990cc25 100644 (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")
        }
index aa26161d2b651cd424ad56a58b39dbefaa2109b6..99456b188d2a6562ebc9b9ddf433995d97e29571 100644 (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{}) {