$Id: 126

$SOId: k1k100ea

If you come from languages like Java, C# or Python, you might be used to the fact that exceptions include call stack for the location that created the exception.

Collecting callstacks is expensive and Go doesn’t add callstack to errors.

Callstacks are useful in debugging. If you’re ok with additional cost, you can use package github.com/pkg/errors to augment errors with callstack.

package main

import (
	"errors"
	"fmt"

	pkgerrors "github.com/pkg/errors"
)

// :show start

func wrappedError() error {
	err := errors.New("Original error")
	// create a new error value which wraps original err and
	// adds calls tack
	return pkgerrors.WithStack(err)
}

func main() {
	// %+v prints original error add callstack
	fmt.Printf("err: %+v\\n\\n", wrappedError())

	// errors created with pkg/errors include callstack by default
	fmt.Printf("err: %+v\\n", pkgerrors.New("error created with pkg/errors"))
}

// :show end

As you can see top part of the callstack includes Go runtime code.