Help us shape the future of Go! Take the 2026 Go Developer Survey

errors

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: MIT Imports: 5 Imported by: 0

README

errors

A lightweight Go utility package that builds on the standard errors with ergonomic helpers for:

  • Creating descriptive errors with or without stack traces
  • Wrapping errors with context (formatted or plain)
  • Preserving and inspecting stack traces across error chains
  • Working with predefined sentinel errors (HTTP-like categories)
  • Using standard errors helpers (Is/As/Unwrap) via re-exports

Note: The package name is errors, so it's recommended to import it with an alias to avoid confusion with the standard library.

import (
    errs "github.com/ceearrashee/errors"
)

Installation

go get github.com/ceearrashee/errors

Quick start

package main

import (
	"fmt"
	"os"

	errs "github.com/ceearrashee/errors"
)

func readConfig(path string) error {
	// Create a basic error with description and capture a stack
	if _, err := os.ReadFile(path); err != nil {
		return errs.Wrap(err, "reading config")
		// or: return errs.NewWithStack("config read failed")
	}
	return nil
}

func main() {
	if err := readConfig("./missing.yaml"); err != nil {
		// Find the last framework error with a stack and print it
		if e := errs.FindOriginalErrorWithStack(err); e != nil {
			fmt.Println("Error:", e.Error())
			fmt.Println("Stack trace:")
			for _, f := range e.GetCallStack() {
				fmt.Println(f)
			}
		} else {
			fmt.Println("Error:", err)
		}
	}
}

Features and API highlights

  • Constructors

    • errs.New(description string) error — simple error with description
    • errs.NewWithStack(description string) error — error with captured stack
    • errs.Newf(format string, args ...any) *errs.Error — formatted description returning the concrete type
  • Wrapping helpers (nil-safe: return nil if original err is nil)

    • errs.Wrap(err error, description string) error
    • errs.Wrapf(err error, format string, args ...any) error
    • errs.WrapWithCustomErr(originalErr, wrappingErr error) error — wraps with a custom sentinel error
    • errs.WrapfWithCustomErr(originalErr, wrappingErr error, format string, args ...any) error
  • Stack utilities

    • errs.FindOriginalErrorWithStack(err error) *errs.Error — the last framework error in the chain that has a stack
    • errs.FindFirstErrorWithStack(err error) error — the first framework error in the chain
    • (*errs.Error).GetCallStack() []string — formatted stack frames
    • errs.AddCustomCallStack(err error, callStack *errs.Stack) error — attach a precomputed stack (advanced)
  • Standard helpers re-exported

    • errs.Is, errs.As, errs.Unwrap are thin wrappers around errors.Is/As/Unwrap
    • errs.Errorf is an alias of fmt.Errorf

Working with predefined errors

This package ships common sentinel errors, useful for categorizing failures (HTTP-like semantics):

  • errs.ErrBadRequest (400)
  • errs.ErrUnauthorized (401)
  • errs.ErrRegistrationRequired (401)
  • errs.ErrPaymentError (402)
  • errs.ErrForbiddenAction (403)
  • errs.ErrNotFound (404)
  • errs.ErrConflict (409)
  • errs.ErrPreconditionFailed (412)
  • errs.ErrValidation (422)
  • errs.ErrInternalServerError (500)

Typical usage:

if err == sql.ErrNoRows {
    return errs.WrapWithCustomErr(err, errs.ErrNotFound)
}

// or with a message
return errs.WrapfWithCustomErr(err, errs.ErrValidation, "invalid input: %s", field)

And checking downstream:

if errs.Is(err, errs.ErrNotFound) {
    // map to HTTP 404 or similar handling
}

// If you need the first predefined error from the chain
var e *errs.Error
if errs.As(err, &e) {
    fmt.Println("predefined:", e.GetOriginalPredefinedError())
}

More examples

  • Simple wrapping with formatted context:
if err := doThing(); err != nil {
    return errs.Wrapf(err, "doing thing %q", id)
}
  • Creating a formatted error directly:
return errs.Newf("user %d not found", userID)
  • Printing the last captured stack from an error chain:
if e := errs.FindOriginalErrorWithStack(err); e != nil {
    for _, frame := range e.GetCallStack() {
        fmt.Println(frame)
    }
}

Best practices

  • Prefer Wrap/Wrapf to add context so the original cause is preserved.
  • For categorization and cross-boundary handling, wrap with predefined sentinels and check via errs.Is.
  • Always import with an alias (e.g., errs) to avoid confusion with the standard library errors package.
  • Wrapping helpers are nil-safe; returning nil if the input error is nil helps reduce boilerplate.

Compatibility

  • Fully compatible with Go's error interfaces and errors.Is/As/Unwrap.
  • The library captures a call stack when you create or wrap using provided helpers.

Version and requirements

  • Module: github.com/ceearrashee/errors
  • Go: 1.20+ recommended (module declares 1.24)

License

This project is licensed under the terms of the MIT License. See the LICENSE file for details.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Is a wrapper for errors.Is.
	Is = stdErrors.Is
	// Unwrap is a wrapper for errors.Unwrap.
	Unwrap = stdErrors.Unwrap
	// As is a wrapper for errors.As.
	As = stdErrors.As
	// Join is a wrapper for errors.Join.
	Join = stdErrors.Join
	// Errorf is a wrapper for fmt.Errorf.
	Errorf = fmt.Errorf //nolint:gochecknoglobals
)
View Source
var (
	ErrBadRequest           = New("bad request")           // HTTP 400
	ErrUnauthorized         = New("user unauthorized")     // HTTP 401
	ErrRegistrationRequired = New("registration required") // HTTP 401
	ErrPaymentError         = New("payment error")         // HTTP 402
	ErrForbiddenAction      = New("forbidden")             // HTTP 403
	ErrNotFound             = New("entity not found")      // HTTP 404
	ErrConflict             = New("conflict request")      // HTTP 409
	ErrPreconditionFailed   = New("precondition failed")   // HTTP 412
	ErrValidation           = New("validation failed")     // HTTP 422
	ErrInternalServerError  = New("internal server error") // HTTP 500
)

errors...

Functions

func AddCustomCallStack

func AddCustomCallStack(err error, callStack *Stack) error

AddCustomCallStack wraps the given error with a custom call stack and returns a new error that includes both. It preserves the original error message while providing additional call stack context useful for debugging.

Parameters:

  • err: The original error to wrap. If nil, returns nil.
  • callStack: The custom call stack to attach to the error. Must be a valid Stack pointer.

Returns:

  • A new Error that embeds both the original error and the provided call stack.
  • nil if the input error is nil.

func FindFirstErrorWithStack

func FindFirstErrorWithStack(err error) error

FindFirstErrorWithStack traverses an error chain to locate the first framework-specific error.

Parameters:

  • err: the root error to traverse

Returns:

  • *Error: the first framework-specific error in the chain, or nil if not found

func FindPublicError added in v1.0.3

func FindPublicError(err error) error

FindPublicError traverses an error chain to locate the first public error that is safe to display to end users.

Parameters:

  • err: the root error to search through

Returns:

  • error: the first public error in the chain, or nil if none are found
Example

ExampleFindPublicError demonstrates finding the first public error in an error chain.

package main

import (
	"fmt"

	"github.com/ceearrashee/errors"
)

func main() {
	// Create a chain of errors with one public error
	internalErr := errors.New("internal database error")
	wrappedErr := errors.Wrap(internalErr, "query failed")
	publicErr := errors.WrapPublic(wrappedErr, "Service temporarily unavailable")
	finalErr := errors.Wrap(publicErr, "handler error")

	// Find the public error
	var frameworkErr *errors.Error
	if errors.As(errors.FindPublicError(finalErr), &frameworkErr) {
		fmt.Println("Found public error:", frameworkErr.Message())
	}

}
Output:
Found public error: Service temporarily unavailable

func New

func New(description string) error

New creates a new Error instance with the specified description.

Parameters:

  • description: a text message describing the error.

Returns:

  • error: an Error instance encapsulating the provided description.

func NewWithStack

func NewWithStack(description string) error

NewWithStack creates a new error with a description and captures the current call stack.

Parameters:

  • description: the error description

Returns:

  • error: a newly created error with stack trace included

func Wrap

func Wrap(err error, description string) error

Wrap wraps an existing error with additional context and a stack trace.

Parameters:

  • err: the original error to wrap
  • description: a description providing context for the error

Returns:

  • error: a wrapped error with the original error, description, and stack trace, or nil if the input error is nil

func WrapPublic added in v1.0.3

func WrapPublic(err error, message string) error

WrapPublic wraps an existing error with a public message that is safe to display to end users.

Parameters:

  • err: the original error to wrap
  • message: a user-friendly public message

Returns:

  • error: a wrapped error marked as public with the original error, message, and stack trace, or nil if the input error is nil
Example

ExampleWrapPublic demonstrates wrapping an error with a public message.

package main

import (
	"fmt"

	"github.com/ceearrashee/errors"
)

func main() {
	internalErr := errors.New("database connection failed")
	publicErr := errors.WrapPublic(internalErr, "Unable to connect to service")

	var frameworkErr *errors.Error
	if errors.As(publicErr, &frameworkErr) {
		fmt.Println("Is public:", frameworkErr.IsPublic())
		fmt.Println("Message:", frameworkErr.Message())
	}

}
Output:
Is public: true
Message: Unable to connect to service

func WrapWithCustomErr

func WrapWithCustomErr(originalErr, wrappingErr error) error

WrapWithCustomErr wraps an original error with a custom error, maintaining context and a call stack.

Parameters:

  • originalErr: the error to be wrapped
  • wrappingErr: the error providing additional context

Returns:

  • error: a new error combining the original and custom errors, or nil if the original error is nil

func Wrapf

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

Wrapf logs the given error with a formatted message and wraps the error with the same message.

func WrapfPublic added in v1.0.3

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

WrapfPublic wraps an existing error with a formatted public message that is safe to display to end users.

Parameters:

  • err: the original error to wrap
  • format: a format string for the public message
  • args: optional arguments for formatting the message

Returns:

  • error: a wrapped error marked as public with formatted message and stack trace, or nil if the input error is nil
Example

ExampleWrapfPublic demonstrates wrapping an error with a formatted public message.

package main

import (
	"fmt"

	"github.com/ceearrashee/errors"
)

func main() {
	internalErr := errors.New("SQL error: syntax error near line 42")
	publicErr := errors.WrapfPublic(internalErr, "Failed to process request #%d", 12345)

	var frameworkErr *errors.Error
	if errors.As(publicErr, &frameworkErr) {
		fmt.Println("Is public:", frameworkErr.IsPublic())
		fmt.Println("Message:", frameworkErr.Message())
	}

}
Output:
Is public: true
Message: Failed to process request #12345

func WrapfWithCustomErr

func WrapfWithCustomErr(originalErr, wrappingErr error, format string, args ...any) error

WrapfWithCustomErr creates a new Error instance by wrapping an original error with a custom error and formatted message.

Parameters:

  • originalErr: the error to wrap; if nil, the function returns nil
  • wrappingErr: the error to use for wrapping the original error
  • format: a format string for the custom error description
  • args: optional arguments for formatting the description

Returns:

  • error: an Error with formatted description and wrapped errors, or nil if the original error is nil

Types

type Error

type Error struct {
	Description string
	// contains filtered or unexported fields
}

Error represents an error structure that includes a description and an error string. It is useful for providing additional context or user-friendly messages alongside the error text.

func FindOriginalErrorWithStack

func FindOriginalErrorWithStack(err error) *Error

FindOriginalErrorWithStack traverses an error chain to locate the latest framework error containing a call stack.

Parameters:

  • err: the root error to search through

Returns:

  • *Error: the last framework error containing a call stack, or nil if none are found

func Newf

func Newf(formatedDescription string, args ...any) *Error

Newf creates a new Error instance with a formatted description.

Parameters:

  • formatedDescription: a string with formatting placeholders for the description
  • args: values to replace the placeholders in the formatted description

Returns:

  • *Error: a pointer to the newly created Error instance with the formatted description set.

func (*Error) Error

func (e *Error) Error() string

Error returns the error message, combining the description and underlying error if present.

Returns:

  • string: the error message, formatted as a string.

func (*Error) Format

func (e *Error) Format(f fmt.State, _ rune)

Format customizes the formatted output of an Error instance.

Parameters:

  • f: the formatter state used for custom formatting
  • _: the rune specifying the format verb (unused)

Returns: none (writes the formatted description to f)

func (*Error) GetCallStack

func (e *Error) GetCallStack() []string

GetCallStack retrieves the function call stack associated with the error.

Returns:

  • []string: a slice of formatted call stack frames as strings, in order from most to least recent.

func (*Error) GetOriginalErrorMessage

func (e *Error) GetOriginalErrorMessage() string

GetOriginalErrorMessage returns the deepest error message in the error chain, optionally prefixed by the error's description.

Returns:

  • string: the error message, formatted as a string.

func (*Error) GetOriginalPredefinedError

func (e *Error) GetOriginalPredefinedError() error

GetOriginalPredefinedError retrieves the first predefined error in the error chain if any exist.

Returns:

  • error: the first predefined error in the chain, or the original error if no predefined error is found.

func (*Error) IsPublic added in v1.0.3

func (e *Error) IsPublic() bool

IsPublic returns whether this error message is safe to display to end users.

Returns:

  • bool: true if the error is marked as public, false otherwise.

func (*Error) Message

func (e *Error) Message() string

Message returns the description if set; otherwise, it returns the underlying error's message.

Returns:

  • string: the error message, formatted as a string.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the wrapped error, enabling error unwrapping in chains and supporting the errors.Unwrap interface.

func (*Error) Wrap

func (e *Error) Wrap(err error) error

Wrap adds context to an existing error using the Error's description.

Parameters:

  • err: the error to wrap; if nil or no description is provided, returns nil.

Returns:

  • error: a new Error instance incorporating the provided error.

Errors:

  • None directly, but may wrap any provided error with additional context.

func (*Error) Wrapf

func (e *Error) Wrapf(format string, err error) error

Wrapf formats and wraps an existing error with the Error's description and a custom message.

Parameters:

  • format: a format string for the error message
  • err: the error to wrap; if nil or no description is provided, returns nil

Returns:

  • error: a new error combining the format, description, and wrapped error

Errors:

  • None directly, but wraps the provided error with formatted context, if present.

type Stack

type Stack []uintptr

Stack represents a slice of uintptrs, typically used to store function call stack pointers.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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