How to get the stacktrace of a panic (and store as a variable)

后端 未结 2 1531
逝去的感伤
逝去的感伤 2021-02-01 14:44

As we all know, panics produce a stacktrace to stdout (Playground link).:

panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
    /tmp/sa         


        
2条回答
  •  走了就别回头了
    2021-02-01 15:04

    Like @Volker mentioned above, and what was posted as a comment, we can use the runtime/debug package.

    package main
    
    import (
        "fmt"
        "runtime/debug"
    )
    
    func main() {
        defer func() {
            if r := recover(); r != nil {
                fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
            }
        }()
    
        var mySlice []int
        j := mySlice[0]
    
        fmt.Printf("Hello, playground %d", j)
    }
    

    prints

    stacktrace from panic: 
    goroutine 1 [running]:
    runtime/debug.Stack(0x1042ff18, 0x98b2, 0xf0ba0, 0x17d048)
        /usr/local/go/src/runtime/debug/stack.go:24 +0xc0
    main.main.func1()
        /tmp/sandbox973508195/main.go:11 +0x60
    panic(0xf0ba0, 0x17d048)
        /usr/local/go/src/runtime/panic.go:502 +0x2c0
    main.main()
        /tmp/sandbox973508195/main.go:16 +0x60
    

    Playground link.

提交回复
热议问题