errors

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2025 License: MIT Imports: 12 Imported by: 5

README

Errors

A lightweight Go errors package with stack tracing and structured fields.

Go Reference Go Report Card Go Version

Features

  • Standard library compatible: Drop-in replacement for errors package
  • 🔍 Automatic stack tracing: Captures call stack when errors are created
  • 📊 Structured fields: Add key-value pairs with With() method
  • 🎨 Multiple formats: Text, JSON, and colorized output
  • 🔗 Error wrapping: Full support for %w verb and error chains
  • High performance: Efficient implementation with object pooling
  • 🔌 Logs integration: Native support for github.com/yanun0323/logs package

⚠️ Caution: using fmt.Errorf to wrap errors is not compatible with errors.Is and errors.As methods.

Installation

go get github.com/yanun0323/errors

Requirements

  • Go 1.21+

Quick Start

import "github.com/yanun0323/errors"

// Create error with fields
err := errors.New("connection failed").
    With(
        "host", "localhost",
        "port", 5432,
    )

// Error wrapping
wrapped := errors.Errorf("database error: %w", err)
// or
wrapped = errors.Wrap(err)
wrapped = errors.Wrap(err, "database error")
wrapped = errors.Wrapf(err, "database %s error", database)

// Format output
println(err.Error())                        // Basic message

errors.Format(err)                          // Text with stack trace
errors.FormatJson(err)                      // JSON text with stack trace
errors.FormatColorized(err)                 // Colorized text with stack trace

fmt.Printf("%s\n", err)                     // Basic message
fmt.Printf("%v\n", err)                     // Formatted text with stack trace
fmt.Printf("%+v\n", err)                    // Formatted & colorized text with stack trace
fmt.Printf("%#v\n", err)                    // JSON text with stack trace

// Error Template
errTmp := errors.NewTemplate("service", "user-service")
errTmpDB := errTmp.With("component", "database")
err1 := errTmpDB.New("connection established")
err2 := errTmpDB.Errorf("query timeout after %d seconds", 30)
err3 := errTmpDB.Wrapf(originalErr, "database operation %d times", 3)

// Logs Package Integration
import "github.com/yanun0323/logs"
logs.WithError(err1).Error("connection established")
logs.WithError(err2).Error("query timeout")
logs.WithError(err3).Error("database operation")

API

Creating Errors
errors.New(text string) Error
errors.Errorf(format string, args ...any) Error
errors.Wrap(err error, args ...any) Error
errors.Wrapf(err error, format string, args ...any) Error
Template

Create error templates with predefined attributes for reuse:

errors.NewTemplate(args ...any) Template
Template Methods
template.With(args ...any) Template             // Add more attributes (chainable)
template.New(text string) Error                 // Create error with template attributes
template.Wrap(err error, args ...any) Error     // Wrap error with template attributes
template.Wrapf(err error, format string, args ...any) Error  // Wrap error with formatted message
template.Errorf(format string, args ...any) Error           // Create formatted error
Error Methods
err.Error() string                          // Standard error message
err.With(args ...any) Error                 // Add fields (chainable)
Standard Functions
errors.Is(err, target error) bool
errors.As(err error, target any) bool
errors.Unwrap(err error) error
Formatting Functions
errors.Format(err error) string             // Text with stack trace
errors.FormatColorized(err error) string    // Colorized text with stack trace
errors.FormatJson(err error) string         // JSON text with stack trace
Logs Package Integration

This package interoperates with the github.com/yanun0323/logs package.

logger := logs.Default()

err := errors.New("database connection failed").
    With(
        "host", "localhost",
        "port", 5432,
    )

logger.WithError(err).Error("Operation error")

When using with the logs package, errors created by this package can be directly passed to log functions and will automatically extract structured fields and stack traces.

Examples

Basic Usage
err := errors.New("validation failed").
    With(
        "field", "email",
        "value", "invalid@",
        "rule", "email_format",
    )
Error Wrapping
original := errors.New("network timeout")
wrapped := errors.Errorf("failed to fetch user: %w", original)
Template Usage
// Create a template with common attributes
errTmp := errors.NewTemplate("service", "user-service", "version", "1.0.0")

// Add more attributes to the template
errTmpDB := errTmp.With("component", "database", "host", "localhost")

// Create errors using the template
err1 := errTmpDB.New("connection failed")
err2 := errTmpDB.Errorf("query timeout after %d seconds", 30)
err3 := errTmpDB.Wrap(originalErr, "database operation failed")
JSON Output
err := errors.New("process failed").With("pid", 1234)
fmt.Printf("%#v\n", err)
// Outputs structured JSON with message, fields, and stack trace
Logs Package Integration
import (
    "github.com/yanun0323/errors"
    "github.com/yanun0323/logs"
)

// Create an error with structured fields
err := errors.New("database connection failed").
    With(
        "host", "localhost",
        "port", 5432,
        "timeout", "30s",
    )

// Pass directly to logs package
logs.Error("Operation failed", err)
// The logs package will automatically extract:
// - Error message
// - Structured attributes (host, port, timeout)
// - Stack trace information
Output Formats
Text
error:
    process user, err: user validation failed, err: root: user not found
cause:
    user not found
field:
    validateUser:
        user_id: 0
        table: users
        func: validateUser
    processUser:
        func: processUser
    handleRequest:
        host: db.example.com
        port: 5432
        timeout: 30s
        func: handleRequest
stack:
    validateUser:
        /Users/Shared/Project/personal/go/errors/example/main.go:58 in validateUser
    processUser:
        /Users/Shared/Project/personal/go/errors/example/main.go:47 in processUser
    handleRequest:
        /Users/Shared/Project/personal/go/errors/example/main.go:34 in handleRequest
    main:
        /Users/Shared/Project/personal/go/errors/example/main.go:18 in main
Colorized

Colorized

JSON
{
  "cause": "user not found",
  "error": "process user, err: user validation failed, err: root: user not found",
  "field": [
    {
      "function": "validateUser",
      "key": "user_id",
      "value": 0
    }
    // ...
  ],
  "stack": [
    {
      "file": "/Users/Shared/Project/personal/go/errors/example/main.go",
      "function": "validateUser",
      "line": "58"
    }
    // ...
  ]
}

Important Notes

⚠️ Do not use fmt.Errorf

Use errors.New or errors.Errorf instead for proper compatibility with errors.Is and errors.As.

License

MIT License

Documentation

Overview

Package errors provides a lightweight error handling library with support for error wrapping, formatting, and error chain checking.

DO NOT use fmt.Errorf to create errors, use errors.New or errors.Errorf instead.

fmt.Errorf is not compatible with errors.Is and errors.As.

fmt.Errorf("failed to process user %d: %w", userID, err)

is not the same as

errors.Errorf("failed to process user %d: %w", userID, err)

Example:

// Create an error
err := errors.New("user validation failed").
	With("user_id", 12345).
	With("email", "user@example.com").
	With("attempt", 3)

// Wrap the error
err = errors.Wrap(err, "using wrap to wrap the error")
err = errors.Errorf("%w can also wrap the error", err)

// Format the error
message := err.Error()
textWithStack := errors.Format(err)
jsonWithStack := errors.FormatJSON(err)
colorizedWithStack := errors.FormatColorized(err)

// using Sprintf to format the error
message := fmt.Sprintf("%s", err)
textWithStack := fmt.Sprintf("%v", err)  // equal to errors.Format(err)
jsonWithStack := fmt.Sprintf("%#v", err)  // equal to errors.FormatJSON(err)
colorizedWithStack := fmt.Sprintf("%+v", err)  // equal to errors.FormatColorized(err)

// Check if the error is a specific error
if errors.Is(err, errors.New("user validation failed")) {
	// handle the error
}

var validationErr AnErrorType
if errors.As(err, &validationErr) {
	// handle the error
}
Example

Example demonstrates how to use the errors package

err1 := New("something went wrong")
fmt.Println(err1.Error())

err2 := &errorStack{
	message: "failed to process user: something went wrong",
	cause:   err1,
	stack:   getStack(0),
	attr:    []attr{},
}
fmt.Println(err2.Error())

err3 := New("database error").
	With("table", "users").
	With("operation", "insert")

fmt.Println(err3.(*errorStack).String())

fmt.Println("JSON:", FormatJson(err3))
fmt.Println("Colorized:", FormatColorized(err3))

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// SkipRuntimeStackTrace is a flag to skip the runtime stack trace
	//
	// It is useful to skip the runtime stack trace when you want to get the error message
	// without the runtime stack trace
	//
	// It is true by default
	SkipRuntimeStackTrace = true
)

Functions

func As

func As(err error, target any) bool

As represents builtin errors.As

func Format

func Format(err error) string

Format formats the error as a string

func FormatColorized

func FormatColorized(err error) string

FormatColorized formats the error as a colorized string

func FormatJson

func FormatJson(err error) string

FormatJson formats the error as a JSON string

func Is

func Is(err, target error) bool

Is represents builtin errors.Is

func Join added in v1.0.2

func Join(errs ...error) error

Join returns an error that wraps the given errors. Any nil error values are discarded. Join returns nil if every value in errs is nil. The error formats as the concatenation of the strings obtained by calling the Error method of each element of errs, with a newline between each string.

A non-nil error returned by Join implements the Unwrap() []error method.

func Unwrap

func Unwrap(err error) error

Unwrap represents builtin errors.Unwrap

Types

type Error

type Error interface {
	error

	With(args ...any) Error
	WithMap(map[string]any) Error
}

Error is an interface that wraps the error interface and provides additional methods

It also implements the error interface, so it can be used as an error

func Errorf

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

Errorf creates a formatted error, supporting '%w' verb for error wrapping

func New

func New(text string) Error

New creates a new error with stack trace

func Wrap

func Wrap(err error, args ...any) Error

Wrap wraps an error and formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.

It has better performance than Errorf with '%w' verb

is the same as

errors.Errorf("%w", err)

func Wrapf

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

Wrapf wraps an error and formats according to a format specifier and returns the resulting string.

It has better performance than Errorf with '%w' verb

is the same as

errors.Errorf("%w", err)

type Template added in v0.0.6

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

Template is a template for creating errors. It contains args that can be used to create an error.

func NewTemplate added in v0.0.6

func NewTemplate(args ...any) Template

NewTemplate creates a new Template.

func (Template) Attrs added in v0.0.6

func (t Template) Attrs(lastCaller frame) []attr

Attrs returns a copy of the template's attributes with the Function field set to the provided lastCaller frame's Function value.

func (Template) Clone added in v1.0.0

func (t Template) Clone() Template

Clone creates a new Template with the same attributes.

func (Template) Errorf added in v0.0.6

func (t Template) Errorf(format string, args ...any) Error

Errorf creates a new formatted Error using the template's attributes. It formats the message using fmt.Sprintf with the provided format and args.

func (Template) New added in v0.0.6

func (t Template) New(text string) Error

New creates a new Error with the given text message and the template's attributes.

func (Template) With added in v0.0.6

func (t Template) With(args ...any) Template

With creates a new Template by appending additional attributes to the existing ones. It returns a new Template instance without modifying the original one.

func (Template) WithMap added in v1.0.6

func (t Template) WithMap(m map[string]any) Template

WithMap creates a new Template by appending additional attributes to the existing ones. It returns a new Template instance without modifying the original one.

func (Template) Wrap added in v0.0.6

func (t Template) Wrap(err error, args ...any) Error

Wrap wraps an existing error with optional additional message arguments. If args are provided, they will be concatenated as the wrap message.

func (Template) Wrapf added in v0.0.6

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

Wrapf wraps an existing error with a formatted message using fmt.Sprintf. If no args are provided, the format string is used as-is.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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