stack

package module
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2020 License: MIT Imports: 3 Imported by: 3

README

Annotation with stack trace for go1.13

GoDoc Report Build Status

Go 1.13 contains support for error wrapping. Now you can add additional information to an error by wrapping it using the new %w verb at fmt.Errorf and examine such errors using errors.Is and errors.As. If you also want to save a stack trace of an error instead of fmt.Errorf use stack.Errorf which is compatible with errors.Is and errors.As and also gives the ability to get a stack trace of the error using stack.Trace function which will return []runtime.Frame.

  • Import.
import "github.com/romanyx/stack
  • Annotate error.
func example() error {
	if err := call(); err != nil {
		return stack.Errorf("call: %w", err)
	}

	return nil
}
  • Print original error.
stack.Origin(err)
  • Iterate through stack trace.
for _, frame := range stack.Trace(err) {
	fmt.Printf("%s:%d %s()\n", frame.File, frame.Line, frame.Function)
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Errorf

func Errorf(format string, a ...interface{}) error

Errorf saves stack trace and pass arguments to fmt.Errorf.

Example
err := stack.Errorf("annotated: %w", errOrigin)
fmt.Println(errors.Is(err, errOrigin))
Output:

true

func Origin

func Origin(err error) error

Origin returns unwrapped origin of the error.

Example
err := frameA()
fmt.Println(stack.Origin(err))
Output:

origin

func Trace

func Trace(err error) []runtime.Frame

Trace returns stack trace for error.

Example
err := frameA()
for _, frame := range stack.Trace(err) {
	fmt.Printf("%s:%d %s()\n", frame.File, frame.Line, frame.Function)
}

// Example output:
// github.com/romanyx/stack/helper_test.go:16 github.com/romanyx/stack_test.frameB()
// github.com/romanyx/stack/helper_test.go:12 github.com/romanyx/stack_test.frameA()
// github.com/romanyx/stack/example_test.go:10 github.com/romanyx/stack_test.ExampleTrance()
// /usr/local/go/src/testing/run_example.go:62 testing.runExample()
// /usr/local/go/src/testing/example.go:44 testing.runExamples()
// /usr/local/go/src/testing/testing.go:1118 testing.(*M).Run()
// _testmain.go:52 main.main()
// /usr/local/go/src/runtime/proc.go:203 runtime.main()
// /usr/local/go/src/runtime/asm_amd64.s:1357 runtime.goexit()
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL