Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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())
Expand Down
22 changes: 22 additions & 0 deletions docs/adr/0002-standard-library-stack-traces.md
Original file line number Diff line number Diff line change
@@ -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.
88 changes: 61 additions & 27 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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"
}

Expand All @@ -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")
}

Expand All @@ -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 {
Expand Down Expand Up @@ -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 != "" {
Expand Down Expand Up @@ -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
}
Expand Down
39 changes: 39 additions & 0 deletions errors_benchmark_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
}
Loading
Loading