试了这个,没作用
defer func() {
r := recover()
if r == nil {
return
}
// stack (copied from net/http/server.go:1284)
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, true)]
ioutil.WriteFile("err.txt", buf, 0644)
os.Exit(1)
}()
package main
import "fmt"
func divideByZero() {
// Use this deferred function to handle errors.
defer func() {
if err := recover(); err != nil {
fmt.Println("HERE")
fmt.Println(err)
fmt.Println(0)
}
}()
// Cause an error.
// ... Go will run the defer func above.
cat := 0
dog := 10 / cat
fmt.Println(dog)
}
func main() {
// Create a divide by zero error and handle it.
divideByZero()
}
#5
更多评论
我明白了,这个函数是可以的,但是每个goroutine都需要执行这个函数。
runtime.Stack(buf, true)可以改成runtime.Stack(buf, false) 只打印本goroutine的错误信息
#1