apperror

package
v1.5.3 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2025 License: BSD-3-Clause Imports: 4 Imported by: 0

Documentation

Overview

Package apperror provides a custom error type that enhances standard Go errors with stack traces and support for additional nested errors.

It is designed to improve error handling in Go applications by offering contextual information such as call location and related errors, especially useful for debugging and logging in production environments.

Features:

  • Attaches a lightweight stack trace to each error
  • Supports wrapping and chaining of multiple related errors
  • Automatically includes detailed trace and error info when debug mode is enabled
  • Implements the standard error interface

Usage:

// Create a new application error
err := apperror.NewError("something went wrong")

// Wrap an existing error to capture a new stack trace point
err = apperror.Wrap(err)

// Add related errors for context
err = err.(apperror.Error).AddError(io.EOF)

// Print with trace and nested errors if debug mode is enabled
fmt.Println(err)

To enable debug output (stack traces), set `flag.Debug = true` before printing errors.

Note: If you're wrapping errors that are already of type `apperror.Error`, prefer `Wrap` over creating a new instance to preserve the trace history.

Index

Constants

This section is empty.

Variables

View Source
var (
	// TraceDelimiter is used to separate trace entries
	TraceDelimiter = " -> "
	// ErrorDelimiter is used to separate multiple errors
	ErrorDelimiter = " => "
	// TraceFormat is the format for displaying trace entries
	TraceFormat = "%v+%v"
	// ErrorFormat is the format for displaying the error message and additional errors
	ErrorFormat = "%s [%s]"
	// ErrorTraceFormat is the format for displaying the error message with a stack trace
	ErrorTraceFormat = "%s | %s"
	// FullFormat is the format for displaying the error message with a stack trace and additional errors
	FullFormat = "%s | %s [%s]"
	// WithDetails is a flag to control whether additional details should be included in the error output
	WithDetails = false
	// FormatDetails is a function that formats additional details for the error
	FormatDetails = func(details map[string]interface{}) string {
		if len(details) == 0 {
			return ""
		}
		var sb strings.Builder
		for key, value := range details {
			if sb.Len() > 0 {
				sb.WriteString(", ")
			}
			sb.WriteString(fmt.Sprintf("%s: %v", key, value))
		}
		return sb.String()
	}

	// ErrorHandler is a function that handles deferred error checks
	ErrorHandler = func(err error, msg string) {
		if flag.Debug {
			panic(fmt.Sprintf(FullFormat, strings.Join(trace(Error{Message: msg}), TraceDelimiter), msg, err.Error()))
		}
		panic(fmt.Sprintf(ErrorFormat, msg, err.Error()))
	}
)

Functions

func Anonymous

func Anonymous(enable bool)

Anonymous enables or disables anonymous caller tracking When enabled, the trace will use package name and line number instead of full file path This can help reduce noise in logs while still providing useful context

func Catch

func Catch(f func() error, msg string)

Catch is a utility function to handle error checks for example in deferred functions It takes an error and a message, and if the error is not nil, it formats the message and panics with the error details. defer apperror.Catch(funcWithError(), "an error occurred")

func CatchCustom

func CatchCustom(f func() error, msg string, handler func(error, string))

CatchCustom is a utility function to handle deferred error checks with a custom handler It takes a function that returns an error, a message, and a custom handler.

func Handle

func Handle(err error, msg string)

Handle is a utility function to handle error checks It takes an error and a message, and if the error is not nil, it formats the message and panics with the error details.

func HandleCustom

func HandleCustom(err error, msg string, handler func(error, string))

HandleCustom is a utility function to handle error checks with a custom handler It takes an error, a message, and a custom handler.

func Split

func Split(err error) (string, []string, []error)

Split separates the error into its components: message, trace, and additional errors It returns the message, a slice of trace strings, and a slice of additional errors

func Where

func Where(level int) string

Where returns the trace location of the caller at the specified level The level parameter indicates how many stack frames to skip

func Wrap

func Wrap(err error) error

Wrap wraps an error and adds a stack trace to it Should be used to wrap errors that are of type Error

Types

type Error

type Error struct {
	Trace   []string
	Errors  []error
	Context map[string]interface{} // Additional context for the error
	Message string
}

Error represents an application error with a stack trace and additional errors It implements the error interface and can be used to wrap other errors

func NewError

func NewError(msg string) Error

NewError creates a new Error instance with the given message If the error is already of type Error you should use Wrap instead

func NewErrorf

func NewErrorf(format string, a ...interface{}) Error

NewErrorf creates a new Error instance with the formatted message If the error is already of type Error you should use Wrap instead

func Parse

func Parse(str string) Error

Parse takes a string representation of an error and returns an Error instance The string should be formatted with TraceDelimiter to separate the trace entries

func (Error) AddDetail

func (e Error) AddDetail(key string, value interface{}) Error

AddDetail adds a key-value pair to the error context This can be used to provide additional information about the error For example, you can add user IDs, request IDs, or any other relevant data

func (Error) AddDetails

func (e Error) AddDetails(details map[string]interface{}) Error

AddDetails adds multiple key-value pairs to the error context This can be used to provide additional information about the error

func (Error) AddError

func (e Error) AddError(err error) Error

AddError adds an additional error to the Error instance context

func (Error) AddErrors

func (e Error) AddErrors(errs []error) Error

AddErrors adds multiple additional errors to the Error instance context

func (Error) Error

func (e Error) Error() string

Error implements the error interface and returns the error message If debug mode is enabled, it includes the stack trace and additional errors

func (Error) GetContext

func (e Error) GetContext() map[string]interface{}

GetContext returns the context map of the error This can be used to retrieve additional information that was added to the error

func (Error) GetDetail

func (e Error) GetDetail(key string) interface{}

GetDetail retrieves a value from the error context by key If the key does not exist, it returns nil

func (Error) Is added in v1.5.3

func (e Error) Is(target error) bool

Is implements the error unwrapping interface for errors.Is() It checks if the target error is equal to this error by comparing their messages

func (Error) Unwrap added in v1.5.3

func (e Error) Unwrap() error

Unwrap implements the error unwrapping interface for errors.Is() and errors.As() It returns the first additional error if any exist, allowing the standard library to traverse the error chain when looking for specific error types

Jump to

Keyboard shortcuts

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