Commit fda5e6d6 authored by Ahsun Ahmed's avatar Ahsun Ahmed Committed by Marcel van Lohuizen

errors: return false if nil error is passed to As

Fixes #30970

Change-Id: I333676b55a2364e329fffeafca8fc57d45a0b84b
Reviewed-on: https://go-review.googlesource.com/c/go/+/168598Reviewed-by: default avatarMarcel van Lohuizen <mpvl@golang.org>
Run-TryBot: Marcel van Lohuizen <mpvl@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
parent 607493be
...@@ -72,7 +72,7 @@ func Is(err, target error) bool { ...@@ -72,7 +72,7 @@ func Is(err, target error) bool {
// matches a type if it is assignable to the target type, or if it has a method // matches a type if it is assignable to the target type, or if it has a method
// As(interface{}) bool such that As(target) returns true. As will panic if // As(interface{}) bool such that As(target) returns true. As will panic if
// target is not a non-nil pointer to a type which implements error or is of // target is not a non-nil pointer to a type which implements error or is of
// interface type. // interface type. As returns false if error is nil.
// //
// The As method should set the target to its value and return true if err // The As method should set the target to its value and return true if err
// matches the type to which target points. // matches the type to which target points.
...@@ -89,7 +89,7 @@ func As(err error, target interface{}) bool { ...@@ -89,7 +89,7 @@ func As(err error, target interface{}) bool {
panic("errors: *target must be interface or implement error") panic("errors: *target must be interface or implement error")
} }
targetType := typ.Elem() targetType := typ.Elem()
for { for err != nil {
if reflectlite.TypeOf(err).AssignableTo(targetType) { if reflectlite.TypeOf(err).AssignableTo(targetType) {
val.Elem().Set(reflectlite.ValueOf(err)) val.Elem().Set(reflectlite.ValueOf(err))
return true return true
...@@ -97,10 +97,9 @@ func As(err error, target interface{}) bool { ...@@ -97,10 +97,9 @@ func As(err error, target interface{}) bool {
if x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) { if x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) {
return true return true
} }
if err = Unwrap(err); err == nil { err = Unwrap(err)
return false
}
} }
return false
} }
var errorType = reflectlite.TypeOf((*error)(nil)).Elem() var errorType = reflectlite.TypeOf((*error)(nil)).Elem()
...@@ -90,6 +90,10 @@ func TestAs(t *testing.T) { ...@@ -90,6 +90,10 @@ func TestAs(t *testing.T) {
target interface{} target interface{}
match bool match bool
}{{ }{{
nil,
&errP,
false,
}, {
wrapped{"pittied the fool", errorT{}}, wrapped{"pittied the fool", errorT{}},
&errT, &errT,
true, true,
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment