打赏

golang panic打印

golang panic打印

(1.)示例代码

package main

import (
    "fmt"
    "os"
  "runtime"
)

func main() {
    defer func() {
        if e := recover(); e != nil {
            panic.PrintStack()
            os.Exit(1)
        }
    }()

    zero := 0
    x := 3 / zero
    fmt.Println("x=", x)
}

// PrintStack 打印堆栈信息
func PrintStack() {
    var buf [4096]byte
    n := runtime.Stack(buf[:], false)
    fmt.Printf("==> %s\n", string(buf[:n]))
}

示例二:

package main

import (
	"fmt"
	"runtime"
)

func stupidCode() {
	n := 0
	fmt.Println(1/ n)
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			for i := 0; ; i++ {
				pc, file, line, ok := runtime.Caller(i)
				if !ok {
					break
				}
				fmt.Println(pc, file, line)
			}
		}
	}()
	stupidCode()
}

package main
 
import (
	"fmt"
	"runtime"
)
 
func stupidCode() {
	n := 0
	fmt.Println(1/ n)
}
 
func main() {
	defer func() {
		if err := recover(); err != nil {
			for i := 0; ; i++ {
				pc, file, line, ok := runtime.Caller(i)
				if !ok {
					break
				}
				fmt.Println(pc, file, line)
			}
		}
	}()
	stupidCode()
}

示例三:


import (
    "fmt"
    "runtime/debug"
)

func test3() {
    // 可以通过 debug.PrintStack() 直接打印,也可以通过 debug.Stack() 方法获取堆栈然后自己打印
    fmt.Printf("%s", debug.Stack())
    debug.PrintStack()
}

参考链接

https://blog.csdn.net/fengfengdiandia/article/details/80058805

https://yuerblog.cc/2019/09/26/golang-利用recover捕获panic异常/

posted @ 2022-06-08 09:46  苍山落暮  阅读(452)  评论(0编辑  收藏  举报