DEV Community

Marcelloh
Marcelloh

Posted on • Updated on

Errors with stack trace in Go

#go

Image description

Introduction

I was always unhappy when it comes to collecting information about the source location of an error. Also the fact that it was sometimes hard to understand which route the program has made to get to that point. That's why I came up with a simple solution: I needed a stack trace.

I've used this for a couple of years now, but then I saw someone complaining that Go didn't offer stack traces. For me that was the trigger to write this, because there is a simple way. Please read until the end :-)

Code information

There is this package which is the solution:
import "github.com/pkg/errors"

To be able to make use of that, each time when you return an error, just wrap it like this:
return errors.Wrap(err, "")
this is functionality from that package

In your main program, where all the error are going to, you just show that trace:
trace.ShowError(err)
this is my own function

Go Playground example

I've made this example, so you can play with it to see how it works.

First:
run it, to see no stack trace

output

Program started
Program finished
Enter fullscreen mode Exit fullscreen mode

Second:
remove the // from line 47
so the line will be active, you'll see the stack trace.
(remark: line 22 is calculated of course from the line of the file, and not the line in the playground editor)

output

Program started
2009/11/10 23:00:00 an error happened
play.groundstart.initialise
    tmpsandbox2363014146startrun.go:22
play.groundstart.Run
    tmpsandbox2363014146startrun.go:9
main.main
    tmpsandbox2363014146prog.go:16
Program finished
Enter fullscreen mode Exit fullscreen mode

Third:
remove the // from line 36
so the line will be active, you'll see the stack trace.

output

Program started
2009/11/10 23:00:00 an error happened
play.groundstart.Run
    tmpsandbox503374963startrun.go:11
main.main
    tmpsandbox503374963prog.go:16
Program finished
Enter fullscreen mode Exit fullscreen mode

Here the link:
https://go.dev/play/p/HOzvDTRo39D

Top comments (0)