forked from pkg/errors
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrorstack.go
More file actions
57 lines (50 loc) · 1.17 KB
/
errorstack.go
File metadata and controls
57 lines (50 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package errorstack
import (
"errors"
"fmt"
"io"
)
// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, WithStack returns nil.
func WithStack(err error) error {
if err == nil {
return nil
}
return &withStack{err, callers()}
}
// GetStack returns the stacktrace of the first error in err's tree has a stacktrace.
// The function returns true if it found such error, and false if there is no error with
// a stack in the err's tree.
func GetStack(err error) (StackTrace, bool) {
var target *withStack
ok := errors.As(err, &target)
if !ok {
return nil, false
}
return target.StackTrace(), true
}
// HasStack returns true if any error in err's tree has a stacktrace.
func HasStack(err error) bool {
var target *withStack
return errors.As(err, &target)
}
type withStack struct {
error
*stack
}
func (w *withStack) Unwrap() error { return w.error }
func (w *withStack) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v", w.Unwrap())
w.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, w.Error())
case 'q':
fmt.Fprintf(s, "%q", w.Error())
}
}