How can I retrieve and store the stacktrace of a Go panic for more detailed debugging?

Susan Sarandon
Release: 2024-11-13 02:23:02
Original
870 people have browsed it

How can I retrieve and store the stacktrace of a Go panic for more detailed debugging?

Retrieving and Storing Stacktraces of Panics

Panics in Go, by default, output a stacktrace to the standard output, providing valuable debugging information. However, recovering from a panic using recover() only returns an error description.

Is there a way to retrieve and store the stacktrace produced during a panic, making it easier to identify the exact location of the issue?

Using the runtime/debug Package

The answer lies in the runtime/debug package. This package provides a mechanism to access and store the stacktrace associated with a panic. Here's how:

package main

import (
    "fmt"
    "runtime/debug"
)

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Panic detected:", r)
            stacktrace := debug.Stack()
            fmt.Println("Stacktrace:", string(stacktrace))
        }
    }()

    // Trigger a panic
    var mySlice []int
    j := mySlice[0] // Index out of bounds panic

    fmt.Printf("Hello, playground %d", j)
}
Copy after login

This code defines a deferred function that handles any panics. When a panic occurs, the recover() function captures the error. Additionally, the debug.Stack() function is used to retrieve the stacktrace associated with the panic and store it as a string variable. Finally, both the error and the stacktrace are printed to the console for debugging purposes.

Running this code will output the following:

Panic detected: runtime error: index out of range
Stacktrace:
goroutine 1 [running]:
main.main.func1()
    /tmp/sandbox773777618/main.go:11 +0x60
panic(0xf9e00, 0x2078e0)
    /usr/local/go/src/runtime/panic.go:502 +0x2c0
main.main()
    /tmp/sandbox773777618/main.go:17 +0x60
Copy after login

In this output, the stacktrace clearly shows the line in the code that caused the panic, providing more valuable debugging information than just the error description.

The above is the detailed content of How can I retrieve and store the stacktrace of a Go panic for more detailed debugging?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template