mirror of https://github.com/golang/go.git
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:
parent
694846a548
commit
c884f6594a
|
|
@ -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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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{}) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue