diff --git a/README.md b/README.md index 2a9276a..b823fec 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ stderrors.Is(validate(""), ErrTitleRequired) // true jerrors.CodeOf(validate("")) // CodeTitleRequired ``` -`Wrap` returns any other top-level `*jerrors.Error` unchanged, so wrapping twice does not add a second stack trace. Stack traces record frames the Go compiler did not inline, so a very small function may not appear as its own frame. +`Wrap` returns any other top-level `*jerrors.Error` unchanged, so wrapping twice does not add a second stack trace. Stack traces are captured with the standard `runtime` package and keep at most 50 frames; a function the Go compiler inlined still appears as its own frame, with its real name and line. ## Extract Codes @@ -159,7 +159,7 @@ Built-in codes carry kinds: `ValRequired`, `ValFormat` and `AppValidation` are v `StackTraceStr` returns a text stack trace. `StackTrace` returns a `slog.Value` group that can be attached to structured logs. `Detail` returns the text of the wrapped cause without the error's own code and friendly message (a wrapped `*Error` keeps its own `[code](message)` prefix). Stack traces and details can contain source paths, function names and other implementation details, so keep them in internal logs only. -The exported `Wrapper` field is deprecated since v0.7.0 and will be removed in v0.8.0: use `Detail` for the cause's text and `StackTrace` or `StackTraceStr` for the stack. +The exported `Wrapper` field, deprecated in v0.7.0, was removed in v0.8.0 together with the `github.com/go-errors/errors` dependency: use `Detail` for the cause's text and `StackTrace` or `StackTraceStr` for the stack. Wrapping a `*goerrors.Error` now captures a fresh stack at the call site instead of reusing its stack. `jgolang/log` v1.7.3 or later is required with v0.8.0. ```go slog.Error("operation failed", "error", err, "stack", err.(*jerrors.Error).StackTrace()) diff --git a/docs/adr/0002-standard-library-stack-traces.md b/docs/adr/0002-standard-library-stack-traces.md new file mode 100644 index 0000000..135938e --- /dev/null +++ b/docs/adr/0002-standard-library-stack-traces.md @@ -0,0 +1,22 @@ +# 0002 — Stack traces use the standard library + +- Status: accepted (2026-11-21) +- Issue: ERR-07 + +## Context + +`errors.Error` exported `Wrapper *goerrors.Error`, which tied the public API of this leaf module to `github.com/go-errors/errors`, its only third-party dependency. The module used it only to capture program counters and turn them into frames, which `runtime.Callers` and `runtime.CallersFrames` already do (KISS-01). `Wrapper` was deprecated in v0.7.0 in favor of `Detail`, `StackTrace` and `StackTraceStr`, and `jgolang/log` stopped reading it in v1.7.3. + +## Decision + +- Remove `Wrapper` and the go-errors dependency in v0.8.0. The module has no third-party dependency. +- `*Error` keeps the wrapped error and the captured program counters in unexported fields. An error has a stack trace exactly when it had a non-nil `Wrapper` before: errors built by `New`, `NewC`, `Wrap`, `With`, `WithC`, `WrapC` and `Wrap` of a `Define` sentinel; not `Define` sentinels or hand-built `&Error{...}` values. +- Constructors capture the stack with `runtime.Callers`, starting at their caller and keeping at most 50 frames (an unexported constant, as in go-errors). +- `StackTrace` and `StackTraceStr` resolve frames with `runtime.CallersFrames` on every call and cache nothing on the shared value, so concurrent reads are race-free (ERR-06). Frame names are split into package and name as go-errors did, so the output format is unchanged. + +## Consequences + +- Breaking change at v0: released as v0.8.0, whose notes name `jgolang/log` v1.7.3 as the minimum `log` version. Code that read `Wrapper` must use `Detail`, `StackTrace` or `StackTraceStr`. +- For frames the compiler did not inline, the output is the same as before. A function inlined into its caller now appears with its real name and line; go-errors repeated the callee or named another function (such as the standard library's `errors.New`) for such frames. +- Wrapping a `*goerrors.Error` no longer reuses its stack: every constructor captures a fresh stack at its call site. +- Creating an error saves one allocation (the `*goerrors.Error`); reading a stack trace allocates as many times as before. diff --git a/errors.go b/errors.go index c0b6bf3..7428674 100644 --- a/errors.go +++ b/errors.go @@ -2,25 +2,27 @@ package errors import ( "log/slog" + "runtime" "strconv" "strings" - "github.com/go-errors/errors" "github.com/jgolang/errors/codes" ) // Error wraps another error with a stack trace, optional friendly message, and optional code. +// The constructors capture the stack trace of their caller with the runtime +// package; read it with StackTrace or StackTraceStr. type Error struct { - // Wrapper holds the wrapped cause and the stack trace captured with it. - // - // Deprecated: use Detail for the wrapped cause's text and StackTrace or - // StackTraceStr for the stack trace. Wrapper exposes - // github.com/go-errors/errors and will be removed in v0.8.0. - Wrapper *errors.Error Message string // A non-technical, user-friendly message describing the error. cause error Code codes.Coder // A custom error code to categorize or identify the error. + // wrapped is the error whose text Detail returns. It is set together with + // stack, so a nil wrapped means the error has no stack trace. + wrapped error + // stack holds the program counters captured by the constructor. + stack *callStack + // defined marks a sentinel built by Define, which Wrap traces at its call site. defined bool } @@ -34,16 +36,16 @@ type Error struct { // Like the stack trace, it can contain implementation details; keep it in // internal logs and return PublicMessage to users. func (err *Error) Detail() string { - if err == nil || err.Wrapper == nil { + if !err.hasStack() { return "" } - return err.Wrapper.Error() + return err.wrapped.Error() } // StackTraceStr returns the stack trace captured when this Error was created. func (err *Error) StackTraceStr() string { - if err == nil || err.Wrapper == nil { + if !err.hasStack() { return "\n\n" } @@ -64,14 +66,14 @@ func (err *Error) StackTraceStr() string { } for _, frame := range frames { - buffer.WriteString(frame.Package) + buffer.WriteString(frame.pkg) buffer.WriteString(".") - buffer.WriteString(frame.Name) + buffer.WriteString(frame.name) buffer.WriteString("\n") buffer.WriteString("· ") - buffer.WriteString(frame.File) + buffer.WriteString(frame.file) buffer.WriteString(":") - buffer.WriteString(strconv.Itoa(frame.LineNumber)) + buffer.WriteString(strconv.Itoa(frame.line)) buffer.WriteString("\n") } @@ -80,32 +82,64 @@ func (err *Error) StackTraceStr() string { // StackTrace returns the stack trace as a slog group value. func (err *Error) StackTrace() slog.Value { - if err == nil || err.Wrapper == nil { + if !err.hasStack() { return slog.GroupValue() } frames := err.stackFrames() var as []slog.Attr for level, frame := range frames { - fmtFrame := frame.File + ":" + strconv.Itoa(frame.LineNumber) + " (" + frame.Name + ")" + fmtFrame := frame.file + ":" + strconv.Itoa(frame.line) + " (" + frame.name + ")" as = append(as, slog.String("frame_"+strconv.Itoa(level), fmtFrame)) } return slog.GroupValue(as...) } -// stackFrames resolves the captured program counters into frames on every call. -// go-errors' StackFrames caches them on the shared Wrapper without -// synchronization, so reading it from several goroutines is a data race. -// NewStackFrame keeps the frame text identical to StackFrames. -func (err *Error) stackFrames() []errors.StackFrame { - callers := err.Wrapper.Callers() - frames := make([]errors.StackFrame, len(callers)) - for i, pc := range callers { - frames[i] = errors.NewStackFrame(pc) +// hasStack reports whether err was built by a constructor that captured a +// stack trace; Define sentinels and hand-built values have none. +func (err *Error) hasStack() bool { + return err != nil && err.wrapped != nil +} + +// stackFrame is one resolved frame of a captured stack trace. +type stackFrame struct { + pkg string + name string + file string + line int +} + +// stackFrames resolves the captured program counters into frames on every +// call. Nothing is cached on the shared *Error, so concurrent reads are safe. +func (err *Error) stackFrames() []stackFrame { + pcs := err.stack.pcs[:err.stack.depth] + frames := make([]stackFrame, 0, len(pcs)) + callersFrames := runtime.CallersFrames(pcs) + for more := len(pcs) > 0; more; { + var frame runtime.Frame + frame, more = callersFrames.Next() + pkg, name := splitFunctionName(frame.Function) + frames = append(frames, stackFrame{pkg: pkg, name: name, file: frame.File, line: frame.Line}) } return frames } +// splitFunctionName splits a fully qualified function name into its package +// path and its name, as go-errors did before v0.8.0 so the printed frames keep +// their format: the package ends at the first "." after the last "/". +func splitFunctionName(function string) (pkg, name string) { + name = function + if lastSlash := strings.LastIndex(name, "/"); lastSlash >= 0 { + pkg = name[:lastSlash+1] + name = name[lastSlash+1:] + } + if period := strings.Index(name, "."); period >= 0 { + pkg += name[:period] + name = name[period+1:] + } + return pkg, strings.ReplaceAll(name, "·", ".") +} + // Unwrap returns the error that caused this Error. func (err *Error) Unwrap() error { if err == nil { @@ -138,7 +172,7 @@ func (err *Error) Error() string { result += " " + err.Message } - if err.Wrapper != nil { + if err.hasStack() { wrapped, onlyPrefix := err.wrappedText() if !onlyPrefix && (codeText == "" || wrapped != codeText) { if result != "" { @@ -168,7 +202,7 @@ func (err *Error) prefix() string { // text, and onlyPrefix reports that nothing else was left to print. func (err *Error) wrappedText() (text string, onlyPrefix bool) { full := err.Detail() - inner, ok := err.Wrapper.Err.(*Error) + inner, ok := err.wrapped.(*Error) if !ok || inner == nil || !sameCode(inner.Code, err.Code) { return full, false } diff --git a/errors_benchmark_test.go b/errors_benchmark_test.go new file mode 100644 index 0000000..91d9bf4 --- /dev/null +++ b/errors_benchmark_test.go @@ -0,0 +1,39 @@ +package errors + +import ( + stderrors "errors" + "testing" + + "github.com/jgolang/errors/codes" +) + +func BenchmarkNewC(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = NewC(codes.AppValidation, "invalid value") + } +} + +func BenchmarkWith(b *testing.B) { + cause := stderrors.New("timeout") + b.ReportAllocs() + for b.Loop() { + _ = With(cause, "loading board") + } +} + +func BenchmarkStackTrace(b *testing.B) { + err := NewC(codes.AppValidation, "invalid value").(*Error) + b.ReportAllocs() + for b.Loop() { + _ = err.StackTrace() + } +} + +func BenchmarkStackTraceStr(b *testing.B) { + err := NewC(codes.AppValidation, "invalid value").(*Error) + b.ReportAllocs() + for b.Loop() { + _ = err.StackTraceStr() + } +} diff --git a/errors_test.go b/errors_test.go index 9373d91..5a64634 100644 --- a/errors_test.go +++ b/errors_test.go @@ -4,6 +4,7 @@ import ( stderrors "errors" "fmt" "log/slog" + "runtime" "strconv" "strings" "sync" @@ -382,7 +383,7 @@ func TestDefineHasNoStack(t *testing.T) { if !ok { t.Fatalf("Expected *Error, got %T", errDefinedTitleRequired) } - if e.Wrapper != nil || len(e.StackTrace().Group()) != 0 { + if len(e.StackTrace().Group()) != 0 || e.StackTraceStr() != "\n\n" || e.Detail() != "" { t.Fatal("Expected a sentinel without a stack trace") } if e.Code.Str() != "PLN-001" || e.Message != "title is required" { @@ -395,10 +396,14 @@ func TestWrapOfDefinedSentinel(t *testing.T) { t.Run("stack starts at the caller", func(t *testing.T) { e, ok := err.(*Error) - if !ok || e.Wrapper == nil { - t.Fatalf("Expected a stacked *Error, got %T", err) + if !ok { + t.Fatalf("Expected *Error, got %T", err) } - if top := e.Wrapper.StackFrames()[0].Name; top != "returnDefinedSentinel" { + frames := e.StackTrace().Group() + if len(frames) == 0 { + t.Fatal("Expected a stack trace") + } + if top := frames[0].Value.String(); !strings.HasSuffix(top, " (returnDefinedSentinel)") { t.Fatalf("Expected top frame returnDefinedSentinel, got %q", top) } }) @@ -573,48 +578,122 @@ func TestStackTraceIsSafeForConcurrentReads(t *testing.T) { wg.Wait() } -func TestStackTraceOutputMatchesGoErrorsFrames(t *testing.T) { +// newCAtKnownLine is not inlined so it appears as its own stack frame; it +// returns the file and line where NewC is called. +// +//go:noinline +func newCAtKnownLine() (err *Error, file string, line int) { + _, file, line, _ = runtime.Caller(0) + err = NewC(codes.AppValidation, "invalid value").(*Error) + return err, file, line + 1 +} + +// withAtKnownLine is not inlined so it appears as its own stack frame; it +// returns the file and line where With is called. +// +//go:noinline +func withAtKnownLine() (err *Error, file string, line int) { + _, file, line, _ = runtime.Caller(0) + err = With(stderrors.New("root cause"), "friendly message").(*Error) + return err, file, line + 1 +} + +func TestStackTraceTopFrameIsTheCaller(t *testing.T) { tests := []struct { - name string - err *Error + name string + build func() (*Error, string, int) + want string }{ - {name: "without message", err: New("root cause").(*Error)}, - {name: "with message", err: With(stderrors.New("root cause"), "friendly message").(*Error)}, + {name: "NewC", build: newCAtKnownLine, want: "newCAtKnownLine"}, + {name: "With", build: withAtKnownLine, want: "withAtKnownLine"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - gotStr := test.err.StackTraceStr() - gotGroup := test.err.StackTrace().Group() + err, file, line := test.build() + location := file + ":" + strconv.Itoa(line) - wantFrames, wantGroup := expectedFrameTexts(test.err) - if !strings.HasSuffix(gotStr, wantFrames) { - t.Fatalf("Expected StackTraceStr to end with\n%s\ngot\n%s", wantFrames, gotStr) + frames := err.StackTrace().Group() + if len(frames) == 0 { + t.Fatal("Expected a stack trace") } - if len(gotGroup) != len(wantGroup) { - t.Fatalf("Expected %d frames, got %d", len(wantGroup), len(gotGroup)) + wantAttr := slog.String("frame_0", location+" ("+test.want+")") + if !frames[0].Equal(wantAttr) { + t.Fatalf("Expected top frame %q, got %q", wantAttr, frames[0]) } - for i, attr := range gotGroup { - if attr.String() != wantGroup[i].String() { - t.Fatalf("Expected frame %d %q, got %q", i, wantGroup[i], attr) - } + + wantStr := "\n\ngithub.com/jgolang/errors." + test.want + "\n· " + location + "\n" + if got := err.StackTraceStr(); !strings.Contains(got, wantStr) { + t.Fatalf("Expected StackTraceStr to contain\n%s\ngot\n%s", wantStr, got) } }) } } -// expectedFrameTexts formats go-errors' own StackFrames the way StackTraceStr -// and StackTrace printed them before ERR-06. -func expectedFrameTexts(err *Error) (string, []slog.Attr) { - var buffer strings.Builder - var attrs []slog.Attr - for level, frame := range err.Wrapper.StackFrames() { - buffer.WriteString(frame.Package + "." + frame.Name + "\n") - buffer.WriteString("· " + frame.File + ":" + strconv.Itoa(frame.LineNumber) + "\n") - fmtFrame := frame.File + ":" + strconv.Itoa(frame.LineNumber) + " (" + frame.Name + ")" - attrs = append(attrs, slog.String("frame_"+strconv.Itoa(level), fmtFrame)) +// newInlinable is small enough for the compiler to inline into its caller. +func newInlinable() error { + return New("inlined") +} + +// callNewInlinable is not inlined; it returns the line where it calls +// newInlinable. +// +//go:noinline +func callNewInlinable() (err *Error, line int) { + _, _, line, _ = runtime.Caller(0) + err = newInlinable().(*Error) + return err, line + 1 +} + +func TestStackTraceNamesInlinedCallers(t *testing.T) { + err, line := callNewInlinable() + + frames := err.StackTrace().Group() + if len(frames) < 2 { + t.Fatalf("Expected at least 2 frames, got %d", len(frames)) + } + if got := frames[0].Value.String(); !strings.HasSuffix(got, " (newInlinable)") { + t.Fatalf("Expected frame 0 newInlinable, got %q", got) + } + want := ":" + strconv.Itoa(line) + " (callNewInlinable)" + if got := frames[1].Value.String(); !strings.HasSuffix(got, want) { + t.Fatalf("Expected frame 1 to end with %q, got %q", want, got) + } +} + +// newAtDepth is not inlined so each recursive call is its own stack frame. +// +//go:noinline +func newAtDepth(depth int) error { + if depth == 0 { + return New("deep") + } + return newAtDepth(depth - 1) +} + +func TestStackTraceKeepsAtMostFiftyFrames(t *testing.T) { + err := newAtDepth(60).(*Error) + + if got := len(err.StackTrace().Group()); got != 50 { + t.Fatalf("Expected 50 frames, got %d", got) + } + if got := strings.Count(err.StackTraceStr(), "\n· "); got != 50 { + t.Fatalf("Expected 50 frames in StackTraceStr, got %d", got) + } +} + +func TestNilErrorHasNoStackOrText(t *testing.T) { + var err *Error + + if got := len(err.StackTrace().Group()); got != 0 { + t.Fatalf("Expected an empty stack trace, got %d frames", got) + } + if got := err.StackTraceStr(); got != "\n\n" { + t.Fatalf("Expected empty stack trace string, got %q", got) + } + if got := err.Error(); got != "" { + t.Fatalf("Expected empty text, got %q", got) } - return buffer.String(), attrs } func TestDetailReturnsWrappedCauseText(t *testing.T) { @@ -654,3 +733,15 @@ func TestDetailOfNilErrorIsEmpty(t *testing.T) { t.Fatalf("Expected empty detail, got %q", got) } } + +// requireComparable fails to compile when T is not comparable. +func requireComparable[T comparable]() {} + +func TestErrorIsComparable(t *testing.T) { + requireComparable[Error]() + + err := NewC(codes.AppValidation, "invalid value").(*Error) + if *err != *err { + t.Fatal("Expected an Error value to equal itself") + } +} diff --git a/functions.go b/functions.go index 102c71f..f60375b 100644 --- a/functions.go +++ b/functions.go @@ -3,11 +3,32 @@ package errors import ( stderrors "errors" "fmt" + "runtime" - "github.com/go-errors/errors" "github.com/jgolang/errors/codes" ) +// maxStackDepth is the most program counters a stack trace keeps, the same +// limit go-errors applied before v0.8.0. +const maxStackDepth = 50 + +// callStack holds captured program counters. It is kept behind a pointer, not +// as a slice field, so that Error stays comparable with ==. +type callStack struct { + pcs [maxStackDepth]uintptr + depth int +} + +// captureStack returns the program counters of the current goroutine's stack. +// skip is the number of frames to leave out, starting with the function that +// calls captureStack: 1 makes the stack start at the caller of a constructor. +func captureStack(skip int) *callStack { + stack := &callStack{} + // 2 leaves out runtime.Callers and captureStack. + stack.depth = runtime.Callers(2+skip, stack.pcs[:]) + return stack +} + // With wraps err with a formatted friendly message and captures a new stack trace. // It keeps the code found anywhere in err's chain, or uses codes.Unknown. func With(err error, message string, args ...interface{}) error { @@ -16,7 +37,8 @@ func With(err error, message string, args ...interface{}) error { } return &Error{ - Wrapper: errors.Wrap(err, 1), + wrapped: err, + stack: captureStack(1), Message: fmt.Sprintf(message, args...), cause: err, Code: codeOrUnknown(err), @@ -30,7 +52,8 @@ func WithC(err error, code codes.Coder, message string, args ...interface{}) err } return &Error{ - Wrapper: errors.Wrap(err, 1), + wrapped: err, + stack: captureStack(1), Message: fmt.Sprintf(message, args...), cause: err, Code: code, @@ -55,7 +78,8 @@ func Wrap(err error) error { } return &Error{ - Wrapper: errors.Wrap(err, 1), + wrapped: err, + stack: captureStack(1), cause: err, Code: codeOrUnknown(err), } @@ -73,7 +97,8 @@ func Define(code codes.Coder, message string) error { // to the sentinel, so errors.Is, errors.As and CodeOf still match it. func traceSentinel(sentinel *Error) error { return &Error{ - Wrapper: errors.Wrap(stderrors.New(sentinel.Message), 2), + wrapped: stderrors.New(sentinel.Message), + stack: captureStack(2), cause: sentinel, Code: sentinel.Code, } @@ -92,7 +117,8 @@ func WrapC(err error, code codes.Coder) error { } return &Error{ - Wrapper: errors.Wrap(cause, 1), + wrapped: cause, + stack: captureStack(1), Message: err.Message, cause: err, Code: code, @@ -100,7 +126,8 @@ func WrapC(err error, code codes.Coder) error { } return &Error{ - Wrapper: errors.Wrap(err, 1), + wrapped: err, + stack: captureStack(1), cause: err, Code: code, } @@ -109,7 +136,8 @@ func WrapC(err error, code codes.Coder) error { // New creates an error with a formatted message, default code, and stack trace. func New(format string, args ...interface{}) error { return &Error{ - Wrapper: errors.Wrap(fmt.Errorf(format, args...), 1), + wrapped: fmt.Errorf(format, args...), + stack: captureStack(1), Code: codes.Unknown, } } @@ -117,7 +145,8 @@ func New(format string, args ...interface{}) error { // NewC creates an error with a code, formatted message, and stack trace. func NewC(code codes.Coder, format string, args ...interface{}) error { return &Error{ - Wrapper: errors.Wrap(fmt.Errorf(format, args...), 1), + wrapped: fmt.Errorf(format, args...), + stack: captureStack(1), Code: code, } } diff --git a/go.mod b/go.mod index 7391701..09caac5 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,3 @@ module github.com/jgolang/errors go 1.26.2 - -require github.com/go-errors/errors v1.5.1 diff --git a/go.sum b/go.sum deleted file mode 100644 index 42387b2..0000000 --- a/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= -github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=