MCPcopy Index your code
hub / github.com/cockroachdb/errors / As

Function As

errutil/as.go:36–72  ·  view source on GitHub ↗

As finds the first error in err's chain that matches the type to which target points, and if so, sets the target to its value and returns true. An error 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

(err error, target interface{})

Source from the content-addressed store, hash-verified

34// - it also supports recursing through causes with Cause().
35// - if it detects an API use error, its panic object is a valid error.
36func As(err error, target interface{}) bool {
37 if target == nil {
38 panic(AssertionFailedf("errors.As: target cannot be nil"))
39 }
40
41 // We use introspection for now, of course when/if Go gets generics
42 // all this can go away.
43 val := reflect.ValueOf(target)
44 typ := val.Type()
45 if typ.Kind() != reflect.Ptr || val.IsNil() {
46 panic(AssertionFailedf("errors.As: target must be a non-nil pointer, found %T", target))
47 }
48 if e := typ.Elem(); e.Kind() != reflect.Interface && !e.Implements(errorType) {
49 panic(AssertionFailedf("errors.As: *target must be interface or implement error, found %T", target))
50 }
51
52 targetType := typ.Elem()
53 for c := err; c != nil; c = errbase.UnwrapOnce(c) {
54 if reflect.TypeOf(c).AssignableTo(targetType) {
55 val.Elem().Set(reflect.ValueOf(c))
56 return true
57 }
58 if x, ok := c.(interface{ As(interface{}) bool }); ok && x.As(target) {
59 return true
60 }
61
62 // If at any point in the single cause chain including the top,
63 // we encounter a multi-cause chain, recursively explore it.
64 for _, cause := range errbase.UnwrapMulti(c) {
65 if As(cause, target) {
66 return true
67 }
68 }
69 }
70
71 return false
72}
73
74var errorType = reflect.TypeOf((*error)(nil)).Elem()

Callers 1

AsFunction · 0.92

Calls 3

UnwrapOnceFunction · 0.92
UnwrapMultiFunction · 0.92
AssertionFailedfFunction · 0.70

Tested by

no test coverage detected