1 | /* |
||
2 | Package e2h its the package of the Enhanced Error Handling module |
||
3 | */ |
||
4 | package e2h |
||
5 | |||
6 | import ( |
||
7 | "fmt" |
||
8 | "runtime" |
||
9 | ) |
||
10 | |||
11 | // This function calls the addTrace in order to create or add stack info |
||
12 | func Trace(e error) error { |
||
13 | 1 | return addTrace(e, "") |
|
14 | } |
||
15 | |||
16 | // Same as Trace, but adding a descriptive message |
||
17 | func Tracem(e error, message string) error { |
||
18 | 1 | return addTrace(e, message) |
|
19 | } |
||
20 | |||
21 | // Same as Tracem, but the descriptive message can have formatted values |
||
22 | func Tracef(e error, format string, args ...interface{}) error { |
||
23 | 1 | return addTrace(e, format, args...) |
|
24 | } |
||
25 | |||
26 | // This is the private function that creates the first EnhancedError |
||
27 | // with info or add the new info to the existing one |
||
28 | func addTrace(err error, format string, args ...interface{}) error { |
||
29 | |||
30 | 1 | if err == nil { |
|
31 | return nil |
||
32 | } |
||
33 | |||
34 | 1 | message := format |
|
35 | 1 | if args != nil { |
|
36 | 1 | message = fmt.Sprintf(format, args...) |
|
37 | } |
||
38 | 1 | pc, file, line, _ := runtime.Caller(2) |
|
39 | 1 | info := StackDetails{ |
|
40 | File: file, |
||
41 | Line: line, |
||
42 | FuncName: runtime.FuncForPC(pc).Name(), |
||
43 | Message: message, |
||
44 | } |
||
45 | |||
46 | 1 | switch err.(type) { |
|
47 | case EnhancedError: |
||
48 | 1 | err.(*enhancedError).stack = append(err.(*enhancedError).stack, info) |
|
49 | 1 | return err |
|
50 | |||
51 | default: |
||
52 | 1 | return &enhancedError{ |
|
53 | err: err, |
||
54 | stack: append(make([]StackDetails, 0), info), |
||
55 | } |
||
56 | } |
||
57 | } |
||
58 |