Increasing Go errors informativeness by adding a stack trace and displaying source fragments

Golang error stack trace with source displayed.
  1. Adds stack trace to error.
  2. Displays source fragments of stack trace (it’s possible if source code exists in runtime environment).

Adding a stack trace to error

// Create a new one.
err := tracerr.New("some error")
// The same with Errorf, which works the same way as fmt.Errorf.
err := tracerr.Errorf("some error %d", num)
// Or wrap an existent error.
err = tracerr.Wrap(err)
func decodeFile(path string, data interface{}) error {
b, err := ioutil.ReadFile(path)
if err != nil {
return tracerr.Wrap(err)
err = json.Unmarshal(b, data)
// You can safely wrap nil, it will be kept as nil.
return tracerr.Wrap(err)

Displaying a stack trace

// Display error message and a stack trace.
// Display error message, stack trace and source code fragments (6 lines by default).
// The same, but in colour, which is more informative.
// You can set up how many lines of source code
// you want to be displayed by passing an additional argument.
tracerr.PrintSource(err, 9)
tracerr.PrintSourceColor(err, 9)
// Or pass 2 additional arguments in order to set up
// how many lines of code to display before and after traced line.
tracerr.PrintSource(err, 5, 2)
tracerr.PrintSourceColor(err, 5, 2)





Software Engineer, Go fan

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

he wasn’t allowed to touch or be in the same room as her husband

The architecture of the Java EJB and how it achieves distributed system features.

Customize ASP.NET Core Web API project and save as template

Docker: Network example

Premium Product: Cloud Functions

Builder Design Pattern

GTD in my Software Architecture journey

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anton G

Anton G

Software Engineer, Go fan

More from Medium

Unit Test in Golang

Dealing with multiple workers - A Go layman approach

Learning Go from Documentation #2 (Call your code from another module)

Hacking sum types with Go generics