// Package xdefer implements an extremely useful function, Errorf, to annotate all errors returned from a function transparently.
package xdefer import ( ) type deferError struct { s string err error frame xerrors.Frame } var _ interface { xerrors.Wrapper xerrors.Formatter Is(error) bool } = deferError{} func ( deferError) () error { return .err } func ( deferError) ( fmt.State, rune) { xerrors.FormatError(, , ) } // Used to detect if there is a duplicate frame as a result // of using xdefer and if so to ignore it. type fakeXerrorsPrinter struct { s []string } func ( *fakeXerrorsPrinter) ( ...interface{}) { .s = append(.s, fmt.Sprint(...)) } func ( *fakeXerrorsPrinter) ( string, ...interface{}) { .s = append(.s, fmt.Sprintf(, ...)) } func ( *fakeXerrorsPrinter) () bool { return true } func ( deferError) ( xerrors.Printer) bool { , := .err.(xerrors.Formatter) if ! { return true } := &fakeXerrorsPrinter{} .frame.Format() := &fakeXerrorsPrinter{} _ = .FormatError() if len(.s) >= 2 && len(.s) >= 3 { if .s[1] == .s[2] { // We don't need to print our frame into the real // xerrors printer as the next error will have it. return false } } return true } func ( deferError) ( xerrors.Printer) error { if .s == "" { if .shouldPrintFrame() { .frame.Format() } return .err } .Print(.s) if .Detail() && .shouldPrintFrame() { .frame.Format() } return .err } func ( deferError) ( error) bool { return xerrors.Is(.err, ) } func ( deferError) () string { if .s == "" { := &fakeXerrorsPrinter{} .frame.Format() if len(.s) < 1 { return .err.Error() } return fmt.Sprintf("%v: %v", strings.TrimSpace(.s[0]), .err) } return fmt.Sprintf("%v: %v", .s, .err) } // Errorf makes it easy to defer annotate an error for all return paths in a function. // See the tests for how it's used. // // Pass s == "" to only annotate the location of the return. func ( *error, string, ...interface{}) { if * != nil { * = deferError{ s: fmt.Sprintf(, ...), err: *, frame: xerrors.Caller(1), } } }