errorx

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2024 License: GPL-3.0 Imports: 8 Imported by: 2

README

errorx

A comprehensive error handling package for Go that provides rich error context, stack traces, and error wrapping capabilities.

Features

  • Detailed stack traces with source line information
  • Error wrapping with cause tracking
  • Prefix support for error context
  • JSON serialization
  • Panic recovery and parsing
  • Full compatibility with Go's standard error interface
  • Comprehensive testing suite

Installation

go get github.com/neumachen/errorx

Key Features

  • Stack Traces: Capture and format detailed stack traces with source line information
  • Error Wrapping: Wrap errors while preserving the original error and adding context
  • Error Context: Add prefixes to errors for better error context
  • Type Information: Access underlying error types and causes
  • JSON Support: Serialize errors to JSON for API responses
  • Source Line Info: Get exact file and line information for debugging
  • Panic Handling: Parse and convert panics into structured errors

Usage

Creating Errors
// Create a new error
err := errorx.New("something went wrong")

// Create a formatted error
err := errorx.Errorf("failed to process %s", item)

// Wrap an existing error
err := errorx.Wrap(existingError, 0)

// Add context with prefix
err := errorx.WrapPrefix(err, "validation failed", 0)
Accessing Error Information
// Get the original cause
cause := err.Cause()

// Get stack frames
frames := err.StackFrames()

// Get error type
errType := err.Type()

// Get formatted stack trace
stack := err.RuntimeStack()

// Get error with context prefix
fmt.Println(err.Error()) // "validation failed: something went wrong"
JSON Output Example
{
  "cause": "something went wrong",
  "stack_frames": [
    {
      "file": "/path/to/file.go",
      "line_number": 42,
      "name": "FunctionName",
      "package": "package/path"
    }
  ],
  "prefix": "validation failed"
}

Documentation

For detailed documentation and examples, see the Go package documentation.

Testing

The package includes a comprehensive test suite. Run the tests with:

go test -v ./...

License

See LICENSE file for details.

Documentation

Overview

Package errorx provides a rich error handling implementation with stack traces and error wrapping capabilities.

Key Features:

  • Stack traces for errors
  • Error wrapping with optional prefixes
  • JSON serialization support
  • Panic parsing and recovery
  • Source line information in stack frames

Core Types and Interfaces:

Error interface extends the standard error interface with additional capabilities:

  • Cause() error: Returns the underlying error
  • StackFrames() []StackFrame: Returns the call stack frames
  • Stack() []uintptr: Returns the raw program counters
  • Prefix() string: Returns any prefix added to the error
  • Type() string: Returns the error type
  • RuntimeStack() []byte: Returns a formatted stack trace

StackFrame type provides detailed information about a single stack frame:

  • File: Source file path
  • LineNumber: Line number in the source file
  • Name: Function name
  • Package: Package path
  • ProgramCounter: Raw program counter value

Key Functions:

Creating Errors:

err := errorx.New("something went wrong")
err := errorx.Errorf("failed to process %s", item)
err := errorx.NewError(existingError)

Wrapping Errors:

err := errorx.Wrap(existingError, 0)
err := errorx.WrapPrefix(existingError, "validation", 0)

Error Comparison:

if errorx.Is(err, target) {
    // Handle specific error
}

Example Usage:

func ProcessItem(item string) error {
    if err := validate(item); err != nil {
        return errorx.WrapPrefix(err, "validation failed", 0)
    }

    result, err := process(item)
    if err != nil {
        return errorx.Errorf("processing failed: %v", err)
    }

    return nil
}

The package is particularly useful in applications that need:

  • Detailed error tracking and debugging
  • Error cause chain analysis
  • Stack trace information
  • Structured error handling

Package errorx provides a comprehensive error handling solution with stack traces and error wrapping.

The package extends Go's standard error interface with additional capabilities like stack traces, error wrapping, and detailed error information. It maintains compatibility with the standard error interface while providing richer error context and debugging capabilities.

Key features:

  • Stack trace capture and formatting
  • Error wrapping with cause tracking
  • Prefix support for error context
  • JSON serialization
  • Runtime stack information
  • Source line lookup

Index

Constants

This section is empty.

Variables

View Source
var MaxStackDepth = 50

MaxStackDepth is the maximum number of stackframes on any error.

Functions

func Is

func Is(comparedTo error, target error) bool

Is detects whether the error is equal to a given error. Errors are considered equal by this function if they are the same object, or if they both contain the same error inside an errors.Error.

Types

type Error

type Error interface {

	// Cause returns the underlying error that caused this error.
	// If this error was created directly and not through wrapping,
	// Cause returns the error itself.
	Cause() error

	// Error returns the error message. If the error has a prefix,
	// it will be included in the message in the format "prefix: message".
	Error() string

	// StackFrames returns the call stack as an array of StackFrame objects,
	// providing detailed information about each call site.
	StackFrames() []StackFrame

	// Stack returns the raw program counters of the call stack.
	// This is useful for low-level stack trace analysis.
	Stack() []uintptr

	// Prefix returns any prefix string that was added to this error
	// through WrapPrefix. Returns empty string if no prefix was set.
	Prefix() string

	// Type returns the underlying error type as a string.
	// For panic errors, it returns "panic".
	Type() string

	// RuntimeStack returns a formatted byte slice containing the
	// full stack trace in the same format as runtime.Stack().
	RuntimeStack() []byte
	// contains filtered or unexported methods
}

Error is the interface that extends Go's standard error interface with additional capabilities for error handling, stack traces, and error wrapping.

The interface provides methods to: - Access the underlying cause of the error - Retrieve stack trace information - Get error context through prefixes - Determine error types - Access formatted stack traces

func Errorf

func Errorf(format string, a ...any) Error

Errorf creates a new error with the given message. You can use it as a drop-in replacement for fmt.Errorf() to provide descriptive errors in return values.

func New

func New(newErrorStr string) Error

func NewError added in v1.0.0

func NewError(newError any) Error

NewError makes an Error from the given value. If that value is already an error then it will be used directly, if not, it will be passed to fmt.Errorf("%v"). The stacktrace will point to the line of code that called NewError.

func ParsePanic

func ParsePanic(panicToParse string) (Error, error)

ParsePanic converts a panic stack trace string into an Error instance. It parses the panic message and stack trace information, creating a structured error with full stack trace information. This is particularly useful for converting recovered panics into error types that can be handled normally.

The function expects the panic string to be in the standard Go runtime format:

panic: <message>

goroutine <id> [<state>]:
<stack trace>

Returns:

  • Error: A structured error containing the panic information
  • error: Any error that occurred during parsing

func Wrap

func Wrap(errToWrap any, stackToSkip int) Error

Wrap makes an Error from the given value. If that value is already an error then it will be used directly, if not, it will be passed to fmt.Errorf("%v"). The stackToSkip parameter indicates how far up the stack to start the stacktrace. 0 is from the current call, 1 from its caller, etc.

func WrapPrefix

func WrapPrefix(e any, prefix string, skip int) Error

WrapPrefix makes an Error from the given value. If that value is already an error then it will be used directly, if not, it will be passed to fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the error message when calling Error(). The skip parameter indicates how far up the stack to start the stacktrace. 0 is from the current call, 1 from its caller, etc.

type StackFrame

type StackFrame struct {
	File           string  `json:"file"`            // The path to the file containing this ProgramCounter
	LineNumber     int     `json:"line_number"`     // The line number in that file
	Name           string  `json:"name"`            // The name of the function that contains this ProgramCounter
	Package        string  `json:"package"`         // The package that contains this function
	ProgramCounter uintptr `json:"program_counter"` // The underlying ProgramCounter
}

StackFrame represents a single frame in an error's stack trace, providing detailed information about the source location, function, and program counter where the error occurred.

Each StackFrame includes:

  • File path and line number of the source code
  • Function name and package path
  • Program counter for low-level debugging
  • Ability to retrieve the actual source line

func NewStackFrame

func NewStackFrame(newProgramCounter uintptr) StackFrame

NewStackFrame populates a StackFrame object from the program counter.

func (StackFrame) Func

func (s StackFrame) Func() *runtime.Func

Func returns the function that contained this frame.

func (*StackFrame) SourceLine

func (s *StackFrame) SourceLine() (string, error)

SourceLine gets the line of code (from File and Line) of the original source if possible.

func (StackFrame) String

func (s StackFrame) String() string

String returns the formatted stack frame, similar to how Go does in runtime/debug.Stack().

Jump to

Keyboard shortcuts

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