Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Print stack trace for error in Go

Printing stack trace can be done %+v in format identifier. However for printf to format the stack trace the error must contain the stack trace that gets added to error. github.com/pkg/errors can be used to attach stack trace while creating a new error.

package main

import (
    "fmt"
    errors "github.com/pkg/errors"
)

func main() {
    _, err := method1()
    fmt.Printf("%+v", err)
}

func method1() (int, error) {
    output, error := nestedMethod()
    wrappedException := errors.Wrap(error, "wrapping error")
    return output, wrappedException
}

func nestedMethod() (int, error) {
    return 2, errors.New("nested exception")
}


Output
nested exception
main.nestedMethod
/Users/user/Documents/sourcecode/go-lang-world/Class.go:20
main.method1
/Users/user/Documents/sourcecode/go-lang-world/Class.go:14
main.main
/Users/user/Documents/sourcecode/go-lang-world/Class.go:9
runtime.main
/Users/user/sdk/go1.18/src/runtime/proc.go:250
runtime.goexit
/Users/user/sdk/go1.18/src/runtime/asm_arm64.s:1259
wrapping error
main.method1
/Users/user/Documents/sourcecode/go-lang-world/Class.go:15
main.main
/Users/user/Documents/sourcecode/go-lang-world/Class.go:9
runtime.main
/Users/user/sdk/go1.18/src/runtime/proc.go:250
runtime.goexit
/Users/user/sdk/go1.18/src/runtime/asm_arm64.s:1259
Process finished with the exit code 0