Debian Codegraph @

errors/wrap.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package errors
6
7 import (
8 "reflect"
9 )
10
11 // An Wrapper provides context around another error.
12 type Wrapper interface {
13 // Unwrap returns the next error in the error chain.
14 // If there is no next error, Unwrap returns nil.
15 Unwrap() error
16 }
17
18 // Opaque returns an error with the same error formatting as err
19 // but that does not match err and cannot be unwrapped.
20 func Opaque(err error) error {
21 return noWrapper{err}
22 }
23
24 type noWrapper struct {
25 error
26 }
27
28 func (e noWrapper) FormatError(p Printer) (next error) {
29 if f, ok := e.error.(Formatter); ok {
30 return f.FormatError(p)
31 }
32 p.Print(e.error)
33 return nil
34 }
35
36 // Unwrap returns the next error in err's chain.
37 // If there is no next error, Unwrap returns nil.
38 func Unwrap(err error) error {
39 u, ok := err.(Wrapper)
40 if !ok {
41 return nil
42 }
43 return u.Unwrap()
44 }
45
46 // Is returns true if any error in err's chain matches target.
47 //
48 // An error is considered to match a target if it is equal to that target or if
49 // it implements an Is method such that Is(target) returns true.
50 func Is(err, target error) bool {
51 if target == nil {
52 return err == target
53 }
54 for {
55 if err == target {
56 return true
57 }
58 if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
59 return true
60 }
61 // TODO: consider supporting target.Is(err). This would allow
62 // user-definable predicates, but also may allow for coping with sloppy
63 // APIs, thereby making it easier to get away with them.
64 if err = Unwrap(err); err == nil {
65 return false
66 }
67 }
68 }
69
70 // As finds the first error in err's chain that matches a type to which target
71 // points, and if so, sets the target to its value and reports success. An error
72 // matches a type if it is of the same type, or if it has an As method such that
73 // As(target) returns true. As will panic if target is nil or not a pointer.
74 //
75 // The As method should set the target to its value and report success if err
76 // matches the type to which target points and report success.
77 func As(err error, target interface{}) bool {
78 if target == nil {
79 panic("errors: target cannot be nil")
80 }
81 typ := reflect.TypeOf(target)
82 if typ.Kind() != reflect.Ptr {
83 panic("errors: target must be a pointer")
84 }
85 targetType := typ.Elem()
86 for {
87 if reflect.TypeOf(err) == targetType {
88 reflect.ValueOf(target).Elem().Set(reflect.ValueOf(err))
89 return true
90 }
91 if x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) {
92 return true
93 }
94 if err = Unwrap(err); err == nil {
95 return false
96 }
97 }
98 }