Documentation
¶
Overview ¶
Package errors provides a modern, lightweight alternative to pkg/errors, capturing a single stack trace at error creation time and preserving it through all wraps. It avoids redundant stack traces while maintaining compatibility with Go 1.13+ errors.Is / errors.As / errors.Unwrap.
The API includes `New`, `Wrap`, `Errorf`, `WithStack`, and `Join`, offering familiar ergonomics without the noise of `WithMessage` or similar.
The *Error type also implements slog.LogValuer for structured logging.
Example (SlogStructuredLogging) ¶
Example_slogStructuredLogging demonstrates how to use slog for structured logging
package main import ( "log/slog" "os" "github.com/stackprune/errors" ) func main() { err := errors.WithStack(errors.New("missing config")) logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) logger.Error("initialization failed", slog.Any("error", err)) // Example output: // { // "time": "2025-06-10T10:01:44.693101023+09:00", // "level": "ERROR", // "msg": "initialization failed", // "error": { // "message": "missing config", // "kind": "*errors.Error", // "stack": [ // "loadConfig at config.go:42", // "main at main.go:10" // ] // } // } }
Index ¶
- func As(err error, target any) bool
- func Errorf(format string, args ...any) error
- func Is(err, target error) bool
- func Join(errs ...error) error
- func New(message string) error
- func NewWithCallers(message string, programCounters []uintptr) error
- func RecoverError(message string) error
- func SetLogOptions(options LogOptions)
- func Unwrap(err error) error
- func WithStack(err error) error
- func Wrap(e error, message string) error
- func Wrapf(e error, format string, args ...any) error
- type Error
- type JoinError
- type LogOptions
- type Stack
- type StackFormat
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Errorf ¶
Errorf formats a message and returns an error with a stack trace.
Example ¶
ExampleErrorf demonstrates formatted error creation.
package main import ( "fmt" "github.com/stackprune/errors" ) func main() { userID := 42 err := errors.Errorf("user %d not found", userID) fmt.Println(err.Error()) }
Output: user 42 not found
func Join ¶
Join combines multiple errors into a single error value, ignoring nils.
Example ¶
ExampleJoin demonstrates joining multiple errors.
package main import ( stderrors "errors" "fmt" "github.com/stackprune/errors" ) func main() { err1 := errors.New("first error") err2 := errors.New("second error") err3 := stderrors.New("third error") joinedErr := errors.Join(err1, err2, err3) fmt.Println(joinedErr.Error()) }
Output: first error second error third error
Example (Single) ¶
ExampleJoin_single demonstrates that joining a single error returns the original error.
package main import ( "fmt" "github.com/stackprune/errors" ) func main() { originalErr := errors.New("single error") joinedErr := errors.Join(originalErr) fmt.Printf("Original: %s\n", originalErr) fmt.Printf("Joined: %s\n", joinedErr) }
Output: Original: single error Joined: single error
Example (WithNil) ¶
ExampleJoin_withNil demonstrates that nil errors are ignored in Join.
package main import ( "fmt" "github.com/stackprune/errors" ) func main() { err1 := errors.New("first error") err2 := errors.New("second error") joinedErr := errors.Join(err1, nil, err2, nil) fmt.Println(joinedErr.Error()) }
Output: first error second error
func New ¶
New creates an error with a message. It initializes an Error struct with the provided message.
Example ¶
ExampleNew demonstrates basic error creation with stack trace.
package main import ( "fmt" "github.com/stackprune/errors" ) func main() { err := errors.New("something went wrong") fmt.Println(err.Error()) }
Output: something went wrong
func NewWithCallers ¶ added in v1.1.0
NewWithCallers creates an error with a message and provided program counters. It allows attaching an external stack trace, e.g., from recover handlers.
func RecoverError ¶ added in v1.1.0
RecoverError creates an error with a message and stack trace. This is a convenience function for defer/recover patterns where you want to capture the current stack trace.
Example ¶
ExampleRecoverError demonstrates error creation from panic recovery.
package main import ( "fmt" "github.com/stackprune/errors" ) func main() { safeFunc := func() (err error) { defer func() { if r := recover(); r != nil { err = errors.RecoverError(fmt.Sprintf("database operation failed: %v", r)) } }() // This will panic panic("connection timeout") } err := safeFunc() fmt.Printf("%+v\n", err) // Example Output: // database operation failed: connection timeout // runtime.gopanic // /usr/local/go/src/runtime/panic.go:770 // github.com/stackprune/errors_test.ExampleRecoverError.func1 // /app/example_test.go:208 // github.com/stackprune/errors_test.ExampleRecoverError // /app/example_test.go:211 }
func SetLogOptions ¶ added in v1.0.0
func SetLogOptions(options LogOptions)
SetLogOptions updates the global LogOptions used for logging *Error values with slog. This affects all future calls to *Error.LogValue. This function is safe for concurrent use.
func Unwrap ¶
Unwrap returns the result of calling the Unwrap method on err, if any.
Example ¶
ExampleUnwrap demonstrates unwrapping errors.
package main import ( "fmt" "github.com/stackprune/errors" ) func main() { baseErr := errors.New("base error") wrappedErr := errors.Wrap(baseErr, "wrapped error") unwrapped := errors.Unwrap(wrappedErr) fmt.Println(unwrapped.Error()) }
Output: base error
func WithStack ¶
WithStack adds a stack trace to the error, if not already present.
Example ¶
ExampleWithStack demonstrates adding stack trace to standard errors.
package main import ( stderrors "errors" "fmt" "github.com/stackprune/errors" ) func main() { standardErr := stderrors.New("standard library error") stackErr := errors.WithStack(standardErr) fmt.Println(stackErr.Error()) }
Output: standard library error
func Wrap ¶
Wrap wraps the given error with a message, preserving the original stack trace.
Example ¶
ExampleWrap demonstrates wrapping an existing error.
package main import ( stderrors "errors" "fmt" "github.com/stackprune/errors" ) func main() { originalErr := stderrors.New("connection failed") wrappedErr := errors.Wrap(originalErr, "database access failed") fmt.Println(wrappedErr.Error()) }
Output: database access failed: connection failed
Example (NetworkError) ¶
ExampleWrap_networkError demonstrates wrapping real-world errors like network timeouts.
package main import ( "fmt" "io" "github.com/stackprune/errors" ) func main() { // Simulate a network error (like io.ErrUnexpectedEOF) networkErr := io.ErrUnexpectedEOF // Wrap with context connectionErr := errors.Wrap(networkErr, "network connection lost") serviceErr := errors.Wrapf(connectionErr, "failed to fetch data from %s", "api.example.com") fmt.Println(serviceErr.Error()) }
Output: failed to fetch data from api.example.com: network connection lost: unexpected EOF
func Wrapf ¶
Wrapf wraps the error with a formatted message, similar to fmt.Sprintf.
Example ¶
ExampleWrapf demonstrates formatted wrapping of an error.
package main import ( stderrors "errors" "fmt" "github.com/stackprune/errors" ) func main() { originalErr := stderrors.New("timeout") tableName := "users" wrappedErr := errors.Wrapf(originalErr, "failed to query table %s", tableName) fmt.Println(wrappedErr.Error()) }
Output: failed to query table users: timeout
Types ¶
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error represents an error with optional stack trace and cause. Implements standard interfaces.
func (*Error) Format ¶
Format implements fmt.Formatter. Use %+v for full stack trace.
Example ¶
ExampleError_Format demonstrates different formatting options.
package main import ( "fmt" "github.com/stackprune/errors" ) func main() { err := errors.New("example error") // Simple string format fmt.Printf("%%s: %s\n", err) // Quoted format fmt.Printf("%%q: %q\n", err) // Simple verbose format fmt.Printf("%%v: %v\n", err) }
Output: %s: example error %q: "example error" %v: example error
Example (StackTrace) ¶
ExampleError_Format_stackTrace demonstrates stack trace formatting with %+v. across handler → usecase → repository layers using Wrap and WithStack.
package main import ( "fmt" "github.com/stackprune/errors" ) func handlerCreateUser() error { if err := usecaseCreateUser(); err != nil { return errors.WithStack(err) } return nil } func usecaseCreateUser() error { if err := repositoryInsertUser(); err != nil { return errors.Wrap(err, "user creation failed") } return nil } func repositoryInsertUser() error { return errors.New("failed to insert user into database") } func main() { err := handlerCreateUser() fmt.Printf("Error: %+v\n", err) // Example output: // Error: user creation failed: failed to insert user into database // github.com/stackprune/errors_test.repositoryInsertUser // /app/example_test.go:133 // github.com/stackprune/errors_test.usecaseCreateUser // /app/example_test.go:125 // github.com/stackprune/errors_test.handlerCreateUser // /app/example_test.go:117 // github.com/stackprune/errors_test.ExampleError_Format_stackTrace // /app/example_test.go:139 }
func (*Error) LogValue ¶ added in v1.0.0
LogValue implements slog.LogValuer for *Error. It returns a structured slog.Value containing the error kind, message, and stack trace. Stack trace formatting is determined by the global LogOptions.
func (*Error) ProgramCounters ¶ added in v1.1.0
ProgramCounters returns the raw program counters (for testing).
type JoinError ¶
type JoinError struct {
// contains filtered or unexported fields
}
JoinError represents a composed error returned by Join. Supports Is and As via Unwrap.
func (*JoinError) Error ¶
Error returns the concatenated error messages from all errors. Multiple errors are joined with newlines.
type LogOptions ¶ added in v1.0.0
type LogOptions struct { MessageKey string KindKey string StackKey string StackFormat StackFormat }
LogOptions defines how *Error values are serialized for slog structured logging. It allows customization of key names and stack trace formatting.
func GetLogOptions ¶ added in v1.0.0
func GetLogOptions() LogOptions
GetLogOptions returns the current global LogOptions. If not explicitly set, default values are used. This function is safe for concurrent use.
type StackFormat ¶ added in v1.0.0
type StackFormat int
StackFormat specifies the output format of stack traces in logs.
const ( // StackFormatStringArray renders the stack trace as an array of strings. StackFormatStringArray StackFormat = iota // StackFormatObjectArray renders the stack trace as an array of structured objects. StackFormatObjectArray )