学一手Golang的recover使用

关于Golang中的 recover


环境:

  • Go v1.12.7
  • MacOS 10.15
  • iris v11.1.1

今天看 iris 源码时看到了它的recover中间件的写法,感觉写的不错,摘录如下

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
// New returns a new recover middleware,
// it recovers from panics and logs
// the panic message to the application's logger "Warn" level.
func New() context.Handler {
return func(ctx context.Context) {
defer func() {
if err := recover(); err != nil {
if ctx.IsStopped() {
return
}

var stacktrace string
for i := 1; ; i++ {
_, f, l, got := runtime.Caller(i)
if !got {
break
}

stacktrace += fmt.Sprintf("%s:%d\n", f, l)
}

// when stack finishes
logMessage := fmt.Sprintf("Recovered from a route's Handler('%s')\n", ctx.HandlerName())
logMessage += fmt.Sprintf("At Request: %s\n", getRequestLogs(ctx))
logMessage += fmt.Sprintf("Trace: %s\n", err)
logMessage += fmt.Sprintf("\n%s", stacktrace)
ctx.Application().Logger().Warn(logMessage)

ctx.StatusCode(500)
ctx.StopExecution()
}
}()

ctx.Next()
}
}

不但使用了 recover 防止程序因为 panic 而退出,而且使用了 runtime.Caller() 打印出错堆栈信息。

我自己写了一个demo,如下

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
package main

import (
"fmt"
"log"
"runtime"
)

func func3() {
panic("something error in func3")
}

func func2() {
func3()
}

func func1() {
func2()
}

func main() {
defer func() {
if err := recover(); err != nil {
var stacktrace string
for i := 1; ; i++ {
_, f, l, got := runtime.Caller(i)
if !got {
break
}
stacktrace += fmt.Sprintf("%s:%d\n", f, l)
}
log.Printf("panic: %v\n" + stacktrace, err)
}
}()
func1()
}

执行后打印结果如下,prefect!

1
2
3
4
5
6
7
8
9
[I] > go run app.go
2019/10/19 19:58:59 panic: something error in func3
/usr/local/Cellar/go/1.12.7/libexec/src/runtime/panic.go:522
/Users/nizhenyang/my-project/algorithm/leetcode/playground/play/recover/app.go:10
/Users/nizhenyang/my-project/algorithm/leetcode/playground/play/recover/app.go:14
/Users/nizhenyang/my-project/algorithm/leetcode/playground/play/recover/app.go:18
/Users/nizhenyang/my-project/algorithm/leetcode/playground/play/recover/app.go:35
/usr/local/Cellar/go/1.12.7/libexec/src/runtime/proc.go:200
/usr/local/Cellar/go/1.12.7/libexec/src/runtime/asm_amd64.s:1337