rogerr

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2025 License: MIT Imports: 6 Imported by: 0

README

rogerr

Build Status Coverage Status Go Report Card Latest version Go Documentation License

A Go package for error handling with structured metadata. Zero dependencies.

Blog post with detailed explanation.

Problem

Error messages that include unique data (user IDs, timestamps, etc.) break error grouping in monitoring tools like Sentry and Rollbar.

Solution

Store unique data as structured metadata separate from the error message. This package attaches metadata to Go's context.Context and preserves it when wrapping errors.

Usage

  1. Create an ErrorHandler: handler := rogerr.NewErrorHandler()
  2. Add metadata to context: ctx = rogerr.WithMetadatum(ctx, "userID", 123)
  3. Wrap errors with metadata: err = handler.Wrap(ctx, err, "operation failed")
  4. Extract metadata for logging: metadata := rogerr.Metadata(err)
Build Options

For cleaner stacktraces, use the -trimpath flag:

go build -trimpath ./cmd/myapp

This shows module-relative paths instead of absolute paths. Skip this if you disable stacktraces with rogerr.WithStacktrace(false).

Full documentation

Documentation

Overview

Package rogerr is a zero-dependency error handling support package.

When creating errors, **do not include goroutine-specific or request-specific information as part of the error message itself**. Error messages with these specific bits of information often break filtering/grouping algorithms, e.g. as used by error reporting tools like Sentry/Rollbar/etc. (If you use Bugsnag, I recommend kinbiko/bugsnag(https://github.com/kinbiko/bugsnag) for an **even better** experience than this package).

Instead this information should be treated as structured data, akin to structured logging solutions like Logrus and Zap. In Go, it's conventional to attach this kind of request specific 'diagnostic' metadata to a `context.Context` type, and that's what this package enables too.

At a high level:

1. Create an ErrorHandler with `handler := rogerr.NewErrorHandler()`. 1. Attach metadata to your context with `rogerr.WithMetadata` or `rogerr.WithMetadatum`. 1. When you come across an error, use `err = handler.Wrap(ctx, err, msg)` to attach the metadata accumulated so far to the wrapped error. 1. Return the error as you would normally, and at the time of logging/reporting, extract the metadata with `md := rogerr.Metadata(err)`. 1. Record the _structured_ metadata alongside the error message.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Metadata

func Metadata(err error) map[string]interface{}

Metadata pulls out all the metadata known by this package as a map[key]value from the given error.

func WithMetadata

func WithMetadata(ctx context.Context, data map[string]interface{}) context.Context

WithMetadata attaches the given keys and values to the rogerr metadata associated with this context. Returns a new context with the metadata attached, or nil if the given ctx was nil.

func WithMetadatum

func WithMetadatum(ctx context.Context, key string, value interface{}) context.Context

WithMetadatum attaches the given key and value to the rogerr metadata associated with this context. Returns a new context with the metadatum attached, or nil if the given ctx was nil.

func Wrap

func Wrap(ctx context.Context, err error, msgAndFmtArgs ...any) error

Wrap wraps errors with the default error handler settings. See ErrorHandler.Wrap for more details. Deprecated: Use ErrorHandler.Wrap instead.

Example
package main

import (
	"context"
	"fmt"

	"github.com/kinbiko/rogerr"
)

func main() {
	handler := rogerr.NewErrorHandler()

	someFuncWithAProblem := func(_ context.Context) error {
		return fmt.Errorf("some low level err")
	}

	someFuncThatWrapsWithRogerr := func(ctx context.Context) error {
		// Attach some projectID to the context as structured metadata
		ctx = rogerr.WithMetadatum(ctx, "projectID", 123)

		err := someFuncWithAProblem(ctx)
		if err != nil {
			return handler.Wrap(ctx, err, "wrap args")
		}
		return nil
	}

	someFuncThatWrapsARogerrError := func(ctx context.Context) error {
		err := someFuncThatWrapsWithRogerr(ctx)
		if err != nil {
			return fmt.Errorf("wrap with fmt: %w", err)
		}
		return nil
	}

	err := someFuncThatWrapsARogerrError(context.Background())
	md := rogerr.Metadata(err)
	fmt.Println(err.Error())     // error message should be cleanly wrapped
	fmt.Println(md["projectID"]) // structured metadata should be available
}
Output:
wrap with fmt: wrap args: some low level err
123

Types

type ErrorHandler added in v1.1.0

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

ErrorHandler provides configurable error handling with optional stacktrace capture.

func NewErrorHandler added in v1.1.0

func NewErrorHandler(opts ...Option) *ErrorHandler

NewErrorHandler creates a new ErrorHandler with the given options. By default, stacktrace capture is enabled.

func (*ErrorHandler) Stacktrace added in v1.1.0

func (h *ErrorHandler) Stacktrace(err error) []Frame

Stacktrace extracts the stacktrace from an error if it was created with ErrorHandler.

func (*ErrorHandler) Wrap added in v1.1.0

func (h *ErrorHandler) Wrap(ctx context.Context, err error, msgAndFmtArgs ...interface{}) error

Wrap attaches ctx data and wraps the given error with message, optionally capturing stacktrace. ctx, err, and msgAndFmtArgs are all optional, but at least one must be given for this function to return a non-nil error. Any attached diagnostic data from this ctx will be preserved should you pass the returned error further up the stack.

type Frame added in v1.1.0

type Frame struct {
	File     string // Full file path
	Line     int    // Line number
	Function string // Function or method name
	InApp    bool   // true if application code, false if dependency
}

Frame represents a single frame in a stacktrace.

type Option added in v1.1.0

type Option func(*ErrorHandler)

Option is a function that configures an ErrorHandler.

func WithStacktrace added in v1.1.0

func WithStacktrace(enabled bool) Option

WithStacktrace configures whether stacktraces should be captured.

Jump to

Keyboard shortcuts

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