stackerr

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 6 Imported by: 0

README

stackerr

stackerr is a lightweight Go library for panic recovery and error handling with customizable stack traces. It simplifies debugging by capturing clean, readable stack traces when panics occur or when errors are explicitly thrown.

Features

  • Panic Recovery: Easily recover from panics and wrap them into errors with stack traces.
  • Clean Stack Traces: Automatically strips noisy arguments and simplifies file paths (e.g., replacing $GOPATH with [Proj]).
  • Customizable: Configure which strings to strip from function names, define custom path replacements, and set stack depth limits.
  • Error Wrapping: Supports standard Go error wrapping (Unwrap()).

Installation

go get github.com/LZStock-OS/stackerr

Usage

Basic Recovery

Use stackerr.Recover in a defer statement to catch panics and populate an error return variable.

package main

import (
	"fmt"
	"github.com/LZStock-OS/stackerr"
)

func riskyOperation() (err error) {
	defer stackerr.Recover(&err)

	// Simulating a panic
	panic("something went wrong")
}

func main() {
	if err := riskyOperation(); err != nil {
		fmt.Printf("Caught error: %v\n", err)
		
		if stack := stackerr.GetStack(err); stack != "" {
			fmt.Println("Stack Trace:")
			fmt.Println(stack)
		}
	}
}
Throwing Errors with Stack Traces

Use stackerr.ThrowPanic to explicitly panic with a wrapped error containing the current stack trace.

func doSomething() {
    err := someInternalFunction()
    if err != nil {
        // This will panic and be caught by a defer stackerr.Recover up the chain
        stackerr.ThrowPanic(fmt.Errorf("operation failed: %w", err))
    }
}
Configuration

You can customize the library's behavior by modifying the global stackerr.Config variable. It is recommended to do this in your init() function or main setup.

import (
    "os"
    "github.com/LZStock-OS/stackerr"
)

func init() {
    // Customize string sequences to strip from function names
    stackerr.Config.StripSequences = []string{"(0", "({", "(*"}
    
    // Set maximum stack depth (default: 10)
    stackerr.Config.MaxStackDepth = 20
    
    // Customize path replacements to hide sensitive paths or make logs shorter
    stackerr.Config.PathReplacements = map[string]string{
        "/home/user/go/src/": "[Src]",
        "github.com/my/project/": "", 
    }
    
    // Redirect log output (default: os.Stderr)
    // Set to nil to disable automatic logging on recovery
    stackerr.Config.Output = os.Stdout 
}

API Reference

func Recover(err *error)

Catches panics, wraps them in a callStackErr, and assigns it to *err. It also logs the panic and stack trace to the configured output.

func ThrowPanic(err error)

Wraps the given error with the current stack trace and panics. Use this when you want to abort execution but preserve context for the recovery handler.

func GetStack(err error) string

Retrieves the stack trace from an error if it was created by Recover or ThrowPanic. Returns an empty string otherwise.

License

MIT

Documentation

Overview

Example (Configuration)

Example_configuration demonstrates how to configure the library.

package main

import (
	"fmt"
	"os"

	"github.com/LZStock-OS/stackerr"
)

func main() {
	// Configure global settings
	stackerr.Config.StripSequences = []string{"(0", "({", "(*"}
	stackerr.Config.MaxStackDepth = 5
	// Disable logging for this example to avoid output mismatch
	stackerr.Config.Output = nil

	var err error
	func() {
		defer stackerr.Recover(&err)
		panic("custom config panic")
	}()

	// Reset config for other tests
	stackerr.Config.Output = os.Stderr

	fmt.Println("Done")

}
Output:

Done

Index

Examples

Constants

View Source
const Version = "v0.1.0"

Version is the current version of the library.

Variables

View Source
var Config = Configuration{
	StripSequences:   defaultStripSequences,
	PathReplacements: GetDefaultPathReplacements(),
	MaxStackDepth:    10,
	Output:           os.Stderr,
}

Config is the global configuration for the library. You can modify this variable directly to configure the library.

Functions

func GetDefaultPathReplacements

func GetDefaultPathReplacements() map[string]string

GetDefaultPathReplacements initializes the default path replacements.

func GetStack

func GetStack(err error) string

GetStack retrieves the stack trace from an error if it is a callStackErr. It returns an empty string if the error does not contain a stack trace.

func Recover

func Recover(err *error)

Recover should be used in defer to handle panics and wrap errors with stack traces. Usage: defer stackerr.Recover(&err)

Example

ExampleRecover demonstrates how to use Recover to catch panics and wrap them with a stack trace.

package main

import (
	"fmt"
	"os"

	"github.com/LZStock-OS/stackerr"
)

func main() {
	// Disable default logging to stderr for this example to keep output clean
	stackerr.Config.Output = nil
	defer func() { stackerr.Config.Output = os.Stderr }() // Restore default

	// Function that might panic
	riskyFunction := func() (err error) {
		// Defer Recover to catch panics and populate err
		defer stackerr.Recover(&err)

		// Simulating a panic
		panic("something went wrong")
	}

	err := riskyFunction()
	if err != nil {
		fmt.Printf("Error caught: %v\n", err)
		// Access the stack trace if needed
		if stack := stackerr.GetStack(err); stack != "" {
			fmt.Println("Stack trace captured.")
		}
	}

}
Output:

Error caught: panic: something went wrong
Stack trace captured.

func ThrowPanic

func ThrowPanic(err error)

ThrowPanic wraps an error with a stack trace and panics.

Example

ExampleThrowPanic demonstrates how to use ThrowPanic to panic with a stack trace.

package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/LZStock-OS/stackerr"
)

func main() {
	// Disable default logging
	stackerr.Config.Output = nil
	defer func() { stackerr.Config.Output = os.Stderr }()

	// Function that throws a panic
	thrower := func() (err error) {
		defer stackerr.Recover(&err)

		// ThrowPanic wraps the error and panics
		stackerr.ThrowPanic(errors.New("critical failure"))
		return nil
	}

	err := thrower()
	if err != nil {
		fmt.Printf("Error caught: %v\n", err)
	}

}
Output:

Error caught: critical failure

Types

type Configuration

type Configuration struct {
	// StripSequences is a list of strings that, if found in a function name,
	// will cause the function name to be truncated from that point.
	// Default: []string{"(0", "({"}
	StripSequences []string

	// PathReplacements is a map of path prefixes to replace in the file path.
	// Default: derived from GOPATH and GOROOT.
	PathReplacements map[string]string

	// MaxStackDepth is the maximum number of stack frames to include.
	// Default: 10
	MaxStackDepth int

	// Output is the writer where panic recovery logs are written.
	// If nil, no logging is done. Default: os.Stderr
	Output io.Writer
}

Configuration holds the configuration for the stackerr library.

Jump to

Keyboard shortcuts

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