Debian Codegraph @

errors/struct.go

raw symbols SCIP
1 package errors
2
3 import "runtime"
4
5 // errorInfo holds a description of an error along with information about
6 // where the error was created.
7 //
8 // It may be embedded in custom error types to add
9 // extra information that this errors package can
10 // understand.
11 type errorInfo struct {
12 // message holds the text of the error message. It may be empty
13 // if underlying is set.
14 message string
15
16 // cause holds the cause of the error as returned
17 // by the Cause method.
18 cause error
19
20 // underlying holds the underlying error, if any.
21 underlying error
22
23 // callerPC holds the program counter of the calling
24 // code that created the error. For some reason, a single
25 // caller PC is not enough to allow CallersFrames
26 // to extract a single source location.
27 callerPC [2]uintptr
28 }
29
30 func newError(underlying, cause error, msg string) error {
31 err := &errorInfo{
32 underlying: underlying,
33 cause: cause,
34 message: msg,
35 }
36 // Skip two frames as we're interested in the caller of the
37 // caller of newError.
38 err.setLocation(2)
39 return err
40 }
41
42 // Underlying returns the underlying error if any.
43 func (e *errorInfo) Underlying() error {
44 return e.underlying
45 }
46
47 // Cause implements Causer.
48 func (e *errorInfo) Cause() error {
49 return e.cause
50 }
51
52 // Message returns the top level error message.
53 func (e *errorInfo) Message() string {
54 return e.message
55 }
56
57 // Error implements error.Error.
58 func (e *errorInfo) Error() string {
59 switch {
60 case e.message == "" && e.underlying == nil:
61 return "<no error>"
62 case e.message == "":
63 return e.underlying.Error()
64 case e.underlying == nil:
65 return e.message
66 }
67 return e.message + ": " + e.underlying.Error()
68 }
69
70 // GoString returns the details of the receiving error message, so that
71 // printing an error with %#v will produce useful information.
72 func (e *errorInfo) GoString() string {
73 return Details(e)
74 }
75
76 func (e *errorInfo) setLocation(callDepth int) {
77 // Technically this might not be correct in the future
78 // because with mid-stack inlining, the skip count
79 // might not directly correspond to the number of
80 // frames to skip.
81 //
82 // If this fails, we'll leave the location as is,
83 // which seems reasonable.
84 var callerPC [2]uintptr
85 if runtime.Callers(callDepth+2, callerPC[:]) == len(callerPC) {
86 e.callerPC = callerPC
87 }
88 }
89
90 // Location implements Locator.
91 func (e *errorInfo) Location() (file string, line int) {
92 frames := runtime.CallersFrames(e.callerPC[:])
93 frame, ok := frames.Next()
94 if ok {
95 return frame.File, frame.Line
96 }
97 return "", 0
98 }