-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
113 lines (104 loc) · 1.87 KB
/
errors.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"errors"
"fmt"
"runtime"
"strings"
)
type (
TracedError interface {
Err() error
Error() string
Stack() []string
Describe(string, ...any)
Trace()
}
exception struct {
err error
msg string
trace []string
}
)
func assert(e interface{}, ntfy ...interface{}) {
var err TracedError
switch e.(type) {
case nil:
case bool:
if !e.(bool) {
mesg := "assertion failed"
if len(ntfy) > 0 {
mesg = ntfy[0].(string)
if len(ntfy) > 1 {
mesg = fmt.Sprintf(mesg, ntfy[1:]...)
}
}
err = &exception{err: errors.New(mesg)}
}
case TracedError:
err = e.(TracedError)
case error:
err = &exception{err: e.(error)}
default:
err = &exception{err: fmt.Errorf("assert: expect error or bool, got %T", e)}
}
if err != nil {
err.Trace()
panic(err)
}
}
func (ex *exception) Trace() {
if len(ex.trace) > 0 {
return
}
n := 1
for {
n++
pc, file, line, ok := runtime.Caller(n)
if !ok {
break
}
f := runtime.FuncForPC(pc)
name := f.Name()
if strings.HasPrefix(name, "runtime.") {
continue
}
fn := strings.Split(file, "/")
if len(fn) > 1 {
file = strings.Join(fn[len(fn)-2:], "/")
}
ex.trace = append(ex.trace, fmt.Sprintf("(%s:%d) %s", file, line, name))
}
}
func (ex *exception) Describe(msg string, args ...interface{}) {
ex.msg = fmt.Sprintf(msg, args...)
}
func (ex exception) Err() error {
return ex.err
}
func (ex exception) Error() string {
msg := ex.msg
if msg == "" {
msg = ex.Err().Error()
}
stack := []string{msg}
for _, t := range ex.trace {
stack = append(stack, "\t"+t)
}
return strings.Join(stack, "\n")
}
func (ex exception) Stack() []string {
return ex.trace
}
func trace(e interface{}) TracedError {
var ex exception
switch err := e.(type) {
case TracedError:
return err
case error:
ex.err = err
default:
ex.err = fmt.Errorf("%v", e)
}
ex.Trace()
return &ex
}