Essential Go Error handling  Suggest an edit

Add callstack to error messages

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.

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"))
}
err: Original error
main.wrappedError
	/books/go/0180-error-handling/add_callstack.go:16
main.main
	/books/go/0180-error-handling/add_callstack.go:21
runtime.main
	/usr/local/Cellar/go/1.10/libexec/src/runtime/proc.go:198
runtime.goexit
	/usr/local/Cellar/go/1.10/libexec/src/runtime/asm_amd64.s:2361

err: error created with pkg/errors
main.main
	/books/go/0180-error-handling/add_callstack.go:24
runtime.main
	/usr/local/Cellar/go/1.10/libexec/src/runtime/proc.go:198
runtime.goexit
	/usr/local/Cellar/go/1.10/libexec/src/runtime/asm_amd64.s:2361

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

  ↑ ↓ to navigate     ↵ to select     Esc to close