Skip to content

Commit 1970d80

Browse files
committed
add crash Handler
1 parent 51a27db commit 1970d80

File tree

3 files changed

+72
-4
lines changed

3 files changed

+72
-4
lines changed

trace/handle_crash.go

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package trace
2+
3+
import "context"
4+
5+
// LogCrashStack for stack
6+
func LogCrashStack(ctx context.Context, r interface{}) {
7+
GetTraceFromContext(ctx).Warnf("panic: %v, detail: %s", r, string(Stacks(false)))
8+
}
9+
10+
// HandleCrash xx
11+
func HandleCrash(fn ...func(r interface{})) {
12+
if r := recover(); r != nil {
13+
for _, f := range fn {
14+
f(r)
15+
}
16+
}
17+
}

trace/handle_crash_test.go

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package trace
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"testing"
8+
)
9+
10+
func TestHandleCrash(t *testing.T) {
11+
crash()
12+
t.Log("still ok")
13+
f()
14+
}
15+
16+
func crash() {
17+
ctx := WithTraceForContext(context.TODO(), "crash-test")
18+
defer HandleCrash(func(r interface{}) {
19+
LogCrashStack(ctx, r)
20+
})
21+
22+
func() {
23+
func() {
24+
panic("do it")
25+
}()
26+
}()
27+
}
28+
29+
func f() {
30+
defer HandleCrash(func(r interface{}) {
31+
log.Printf("recover from: %v", r)
32+
})
33+
34+
fmt.Println("Calling g.")
35+
g(0)
36+
fmt.Println("Returned normally from g.")
37+
}
38+
39+
func g(i int) {
40+
if i > 3 {
41+
fmt.Println("Panicking!")
42+
panic(fmt.Sprintf("%v", i))
43+
}
44+
defer fmt.Println("Defer in g", i)
45+
fmt.Println("Printing in g", i)
46+
g(i + 1)
47+
}

trace/trace.go

+8-4
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ type Trace interface {
5757
// Errorf will print the args with a format as the error level log
5858
Errorf(format string, args ...interface{})
5959
// Stack will return current stack
60-
Stack() string
60+
Stack(all ...bool) string
6161
// String will return a string-serialized trace
6262
String() string
6363
}
@@ -170,7 +170,7 @@ func (t *trace) Duration() time.Duration {
170170
}
171171

172172
// copy this from glog
173-
func stacks(all bool) []byte {
173+
func Stacks(all bool) []byte {
174174
n := 10000
175175
if all {
176176
n = 100000
@@ -191,8 +191,12 @@ func (t *trace) String() string {
191191
return t.header()
192192
}
193193

194-
func (t *trace) Stack() string {
195-
return string(stacks(true))
194+
func (t *trace) Stack(all ...bool) string {
195+
dumpAll := false
196+
if len(all) > 0 {
197+
dumpAll = all[0]
198+
}
199+
return string(Stacks(dumpAll))
196200
}
197201

198202
func (t *trace) log(out func(depth int, args ...interface{}), args ...interface{}) {

0 commit comments

Comments
 (0)