ergo

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 7 Imported by: 0

README

ergo

Go Reference

日本語

A structured error handling library for Go with attributes, error codes, and stack traces.

Features

  • Structured Attributes: Attach contextual information to errors using log/slog.Attr
  • Error Codes: Associate typed codes with errors
  • Stack Traces: Automatically capture stack traces
  • Error Wrapping: Wrap errors while preserving context

Installation

go get github.com/newmo-oss/ergo

Usage

Creating Errors
import (
    "log/slog"

    "github.com/newmo-oss/ergo"
)

// Simple error
// Stack trace is automatically attached
err := ergo.New("failed to process request")

// With attributes
err := ergo.New("user not found", slog.String("user_id", "12345"), slog.Int("status_code", 404))
Wrapping Errors
// Wrap with additional context
// Stack trace is attached if not present
if err := doSomething(); err != nil {
    return ergo.Wrap(err, "failed to execute operation", slog.String("operation", "process"))
}
Error Codes
// Define error codes
// NewCode automatically captures the package path from the stack trace,
// so codes with the same key name from different packages can be distinguished
var (
    ErrCodeNotFound = ergo.NewCode("NotFound", "resource not found")
    ErrCodeInvalid  = ergo.NewCode("Invalid", "invalid input")
)

func doSomething() error {
    // Create error
    err := ergo.New("user not found", slog.String("user_id", "12345"))

    // Add code to error
    err = ergo.WithCode(err, ErrCodeNotFound)

    // Retrieve error code
    code := ergo.CodeOf(err)
    if code == ErrCodeNotFound {
        // handle not found error
    }

    // String representation of error code
    // Formatted as: package-path.Key: Message
    fmt.Println(code.String()) // github.com/yourorg/yourapp/service.NotFound: resource not found
}
Retrieving Attributes
// Iterate over all attributes (including parent errors)
for attr := range ergo.AttrsAll(err) {
    fmt.Printf("%s: %v\n", attr.Key, attr.Value)
}
Stack Traces
// Get stack trace
st := ergo.StackTraceOf(err)
if st != nil {
    fmt.Printf("Stack trace: %v\n", st)
}
Sentinel Errors
// Always use NewSentinel for package-level constants
// NewSentinel creates lightweight errors without stack traces, attributes, or error codes
var (
    ErrInvalidInput = ergo.NewSentinel("invalid input")
    ErrTimeout      = ergo.NewSentinel("operation timeout")
)

// Compare with sentinel errors
if errors.Is(err, ErrTimeout) {
    // handle timeout
}

For more details on sentinel errors, see Dave Cheney's article.

Formatting
err := ergo.New("operation failed", slog.String("key1", "value1"), slog.Int("key2", 100))
fmt.Printf("%v\n", err)   // operation failed
fmt.Printf("%+v\n", err)  // operation failed: key1=value1,key2=100

Static Analysis: ergocheck

A static analyzer that enforces consistent usage of ergo and checks for best practices. See ergocheck/README.md for details.

License

MIT License - see LICENSE for details.

Contributing

Issues and Pull Requests are welcome.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AttrsAll

func AttrsAll(err error) iter.Seq[slog.Attr]

AttrsAll returns an iterator that iterates over the attributes of the given error and its parent ones. If the parent of the error has the same attribute key as the children, the children are iterated over the parent.

func New

func New(msg string, attrs ...slog.Attr) error

New creates a new error with given attributes. The attributes can be retrieved using AttrsAll. The error has a stacktrace of the callers. The stacktrace can be obtained via StackTraceOf. If you would like to create an error into a package variable, you must use NewSentinel.

func NewSentinel

func NewSentinel(msg string) error

NewSentinel creates a new sentinel error. The sentinel error does not have a stacktrace, any attributes and an error code.

func StackTraceOf

func StackTraceOf(err error) caller.StackTrace

StackTraceOf returns stacktrace of the given error. If err does not have stacktrace, StackTraceOf returns nil.

func WithCode

func WithCode(err error, code Code) error

WithCode creates a new error which associated with the given code and the parent error. The code can be obtained via CodeOf.

func Wrap

func Wrap(parent error, msg string, attrs ...slog.Attr) error

Wrap creates a new wrapped error of the parent error with given attributes. The attributes can be retrieved using AttrsAll. The error has a stacktrace of the callers. The stacktrace can be obtained via StackTraceOf. Calling errors.Unwrap with the wrapped error returns the parent error.

Types

type Code

type Code struct {
	// contains filtered or unexported fields
}

Code is an error code that can be associated with an error using WithCode.

func CodeOf

func CodeOf(err error) Code

CodeOf returns the associated code with the error.

func NewCode

func NewCode(key, message string) Code

NewCode creates new error code with the key and the message.

func (Code) IsZero

func (code Code) IsZero() bool

IsZero returns whether code is zero value or not.

func (Code) Key

func (code Code) Key() string

Key returns the key of error code.

func (Code) Message

func (code Code) Message() string

Message returns the message of error code.

func (Code) PkgPath

func (code Code) PkgPath() string

PkgPath returns the import path of the package the code belongs to The import path which is from the stack trace of calling NewCode.

func (Code) String

func (code Code) String() string

String implements fmt.Stringer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL