Skip to content

Commit

Permalink
errors: return false if nil error is passed to As
Browse files Browse the repository at this point in the history
Fixes golang#30970

Change-Id: I333676b55a2364e329fffeafca8fc57d45a0b84b
Reviewed-on: https://go-review.googlesource.com/c/go/+/168598
Reviewed-by: Marcel van Lohuizen <[email protected]>
Run-TryBot: Marcel van Lohuizen <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
  • Loading branch information
ahsun-ahmed authored and mpvl committed Apr 10, 2019
1 parent 607493b commit fda5e6d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/errors/wrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
// 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
// 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
// matches the type to which target points.
Expand All @@ -89,18 +89,17 @@ func As(err error, target interface{}) bool {
panic("errors: *target must be interface or implement error")
}
targetType := typ.Elem()
for {
for err != nil {
if reflectlite.TypeOf(err).AssignableTo(targetType) {
val.Elem().Set(reflectlite.ValueOf(err))
return true
}
if x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) {
return true
}
if err = Unwrap(err); err == nil {
return false
}
err = Unwrap(err)
}
return false
}

var errorType = reflectlite.TypeOf((*error)(nil)).Elem()
4 changes: 4 additions & 0 deletions src/errors/wrap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ func TestAs(t *testing.T) {
target interface{}
match bool
}{{
nil,
&errP,
false,
}, {
wrapped{"pittied the fool", errorT{}},
&errT,
true,
Expand Down

0 comments on commit fda5e6d

Please sign in to comment.