ctxerrors

package module
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 5 Imported by: 22

README

ctxerrors

Go Reference CI coverage version license imported by

 ####  ##### #    # ###### #####  #####   ####  #####   ####  
#    #   #    #  #  #      #    # #    # #    # #    # #      
#        #     ##   #####  #    # #    # #    # #    #  ####  
#        #     ##   #      #####  #####  #    # #####       # 
#    #   #    #  #  #      #   #  #   #  #    # #   #  #    # 
 ####    #   #    # ###### #    # #    #  ####  #    #  ####  

fuck yeah, another Go error handling package 🖕

A Go library that wraps errors with context information (file, line, function) because debugging without context is like trying to find your dick in the dark.

Table of Contents

Installation

go get github.com/psyb0t/ctxerrors

Needs Go 1.26 or newer. The library itself imports only the standard library.

What the fuck does it do?

This package automatically captures where your errors happen in your code. No more hunting through logs like some dickless detective wondering where the fuck that error came from.

  • New() creates a new error with location context.
  • Wrap() wraps an existing error with additional context and location.
  • Wrapf() is Wrap() with printf-style formatting, because we're not animals.
  • Join() squashes a pile of errors into one that still knows where they got squashed. For when one thing fans out and several bits can shit the bed independently: three log sinks, a batch of rows, whatever.
  • SetErrorMap() / MapError() / ClearErrorMap() translate foreign sentinel errors (gorm, sql, redis...) into your own business errors at wrap time.

New(), Wrap(), Wrapf() and Join() return a plain error holding a *CTXError, which supports errors.Unwrap(), errors.Is() and errors.As() because Go's error handling conventions aren't completely ass-backwards. Wrap(nil, ...) and Wrapf(nil, ...) return nil and log the call site through log/slog, and Join() returns nil when everything you gave it is nil. The error map functions don't return anything; they just manage the translation map.

Usage

import "github.com/psyb0t/ctxerrors"

func processFile(filename string) error {
    file, err := os.Open(filename)
    if err != nil {
        return ctxerrors.Wrap(err, "failed to open file")
    }
    defer file.Close()

    // do stuff...

    return nil
}

func writeToAllSinks(sinks []Sink, record Record) error {
    var errs []error

    for i, sink := range sinks {
        if err := sink.Write(record); err != nil {
            errs = append(errs, ctxerrors.Wrapf(err, "sink %d failed", i))
        }
    }

    return ctxerrors.Join(errs...)
}

Wrapping errors covers every function, the nil handling and how errors.Is/errors.As see the result.

Error output

When shit hits the fan, you get detailed context:

failed to connect to database at localhost:5432: dial tcp [::1]:5432: connect: connection refused [/path/to/your/file.go:42 in main.connectToDatabase]

Wrap it again and every layer adds its own location, so one line shows the whole path the error took. Error output has the exact format, longer chains, and what Go does to your closure names in the trace.

Error mapping

Stop foreign errors from leaking through your layers. Register a translation map at startup and Wrap/Wrapf tag matching driver errors with your own business errors while wrapping:

ctxerrors.SetErrorMap(map[error]error{
    gorm.ErrRecordNotFound: commerr.ErrNotFound,
    gorm.ErrDuplicatedKey:  commerr.ErrAlreadyExists,
})

The wrapped error matches both commerr.ErrNotFound and the original gorm error with errors.Is, and Error() prints the mapped sentinel so driver details stay out of logs. CTXError.Original() hands you the raw cause when you really need it. The matching rules are on Error mapping.

Common sentinels

commerr is the shared sentinel vocabulary (not-found, already-exists, timeout, the usual suspects) that every service ends up needing, parked in a subpackage so importing ctxerrors just to wrap shit doesn't drag the whole list in:

import "github.com/psyb0t/ctxerrors/commerr"

func GetUser(id int) (*User, error) {
    if id <= 0 {
        return nil, commerr.ErrInvalidArgument
    }
    // ...
    return nil, commerr.ErrNotFound
}

They're plain errors.New sentinels, so errors.Is(err, commerr.ErrNotFound) keeps holding no matter how many times you Wrap it. All 60 of them, with their messages, are on Common sentinels.

Documentation

The full docs live at psyb0t.github.io/ctxerrors.

Page What's in it
Wrapping errors New, Wrap, Wrapf, Join, nil handling, unwrapping
Error output The exact Error() format and a pile of stupid examples
Error mapping Translating driver errors, matching rules, Original() and Mapped()
Common sentinels Every commerr sentinel and its message
API reference Every exported function and method
Development Make targets, coverage gate, CI and releases

Sponsor

Buy Me a Coffee

License

MIT License, because lawyers are expensive and I don't want to deal with that shit

Why?

Because Go's error handling is verbose as fuck and debugging without context is like trying to find your asshole with both hands tied behind your back. This shit makes it slightly less painful.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearErrorMap added in v0.3.0

func ClearErrorMap()

ClearErrorMap removes all mappings.

func Join added in v0.4.0

func Join(errs ...error) error

Join combines several errors into one that carries the call site, for the case where an operation fans out and more than one branch can fail independently — several sinks written to, several items in a batch. nil errors are ignored, and Join returns nil when every error is nil.

The result unwraps to what the standard library's errors.Join produces, so errors.Is and errors.As still find any of the joined errors.

func MapError added in v0.3.0

func MapError(from, to error)

MapError registers a single translation from -> to. Useful for incremental registration across packages in init(). No-op if either err is nil.

func New

func New(message string) error

New creates a new error with context but without wrapping another error.

func SetErrorMap added in v0.3.0

func SetErrorMap(m map[error]error)

SetErrorMap replaces the global translation map. Intended to be called once at startup. Entries with a nil key or nil value are skipped.

func Wrap

func Wrap(err error, message string) error

Wrap wraps an error with context information (file, line, and function name).

func Wrapf

func Wrapf(err error, format string, args ...any) error

Wrapf wraps an error with context information (file, line, and function name).

Types

type CTXError added in v0.2.0

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

CTXError holds the wrapped error and additional context.

func (*CTXError) As added in v0.8.0

func (e *CTXError) As(target any) bool

As finds the first error in the error map's translation of the wrapped error that matches target. errors.As falls back to the original chain through Unwrap when this reports false.

func (*CTXError) Error added in v0.2.0

func (e *CTXError) Error() string

Error returns the formatted error message, including file and function details. When the error map translated the wrapped error, the message shows the translation, not the original error.

func (*CTXError) Is added in v0.8.0

func (e *CTXError) Is(target error) bool

Is reports whether the error map's translation of the wrapped error matches target. errors.Is calls it before following Unwrap, so a wrapped error matches both its translation and everything in its original chain.

func (*CTXError) Mapped added in v0.9.0

func (e *CTXError) Mapped() error

Mapped returns the error map's translation of the wrapped error, or nil when no entry matched.

func (*CTXError) Original added in v0.9.0

func (e *CTXError) Original() error

Original returns the error passed to Wrap or Wrapf, before any error map translation, or nil when e wraps nothing. Its message is never part of Error() once a translation applied, so reach for it only when the raw cause is really needed, for example in internal diagnostics.

func (*CTXError) Unwrap added in v0.2.0

func (e *CTXError) Unwrap() error

Unwrap retrieves the underlying error, if any. It is the original error, never the error map's translation, which Is and As report as well.

Directories

Path Synopsis
Package commerr provides common, general-purpose sentinel errors — not-found, already-exists, invalid-argument, timeout, unavailable, and the like — so any Go code can return and match a shared one with errors.Is instead of re-declaring the same errors in every package.
Package commerr provides common, general-purpose sentinel errors — not-found, already-exists, invalid-argument, timeout, unavailable, and the like — so any Go code can return and match a shared one with errors.Is instead of re-declaring the same errors in every package.

Jump to

Keyboard shortcuts

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