36

stack - Same as fmt.Errorf but with stack trace.

 4 years ago
source link: https://github.com/romanyx/stack
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Annotation with stack trace for go1.13

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)
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK