xerrors

package
v0.9.4-rc Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 8 Imported by: 0

README

xerrors

Structured error classification and logging utilities for corporate Go applications.

 

This package provides a rich error abstraction layer for Go. It supports domain-specific error codes, component tracing, structured debug output, and integration with Go's slog logging framework.


Purpose

xerrors is designed to standardize error handling and observability across the repository. It provides:

  • xerrors.NewError — create a rich DetailedError with domain code, message, data, and component tracing.
  • xerrors.NewErr — factory for formatted or corporate-style errors using the XERR_ token family.
  • xerrors.Log — publish structured error logs via slog.
  • xerrors.WithLogCallerSkip — adjust caller frame tracing for wrapped logging helpers.

The package improves troubleshooting by keeping error metadata structured, traceable, and consistent across logging channels.


Installation

Use go get pointing to the package module:

  go get github.com/AeonDigital/Go-Core/xerrors@latest

In your code, import the package:

import (
    "context"
    "errors"
    "log/slog"

    "github.com/AeonDigital/Go-Core/xerrors"
)

Basic usage

Create a detailed error instance and log it with structured attributes:

err := errors.New("database connection failed")
richErr := xerrors.NewError(
    xerrors.ErrUnknown,
    err,
    "database initialization error",
    `{"retries":3}`,
)

xerrors.Log(
    context.Background(),
    richErr,
    []slog.Attr{
        slog.String("service", "auth"),
    },
)

The NewErr helper also supports formatted corporate tokens:

err := xerrors.NewErr(
    xerrors.XERR_NOT_FOUND,
    "DB",
    "resource not found",
    "database",
    "users",
    errors.New("missing row"),
)

To adjust caller frame detection when Log is wrapped by a helper:

xerrors.Log(ctx, err, nil, xerrors.WithLogCallerSkip(1))

Supported APIs

The package exposes:

  • xerrors.DetailedError — interface for rich error payloads.
  • xerrors.NewError — build structured errors with component and debug payloads.
  • xerrors.NewErr — format plain or token-driven runtime errors.
  • xerrors.Log — emit structured slog records.
  • xerrors.WithLogCallerSkip — configure call-site tracing.

It also defines a set of error classification constants such as:

  • xerrors.ErrUnknown
  • xerrors.XERR_FIELD_REQUIRED
  • xerrors.XERR_NOT_FOUND
  • xerrors.XERR_INVALID_FORMAT
  • xerrors.XERR_MUTUAL_EXCLUSIVITY_VIOLATION

External dependencies

xerrors depends only on the Go standard library:

  • context
  • errors
  • fmt
  • log/slog
  • runtime
  • strings

No third-party packages are required by this package.

Documentation

Index

Constants

View Source
const (
	// ErrUnknown serves as the general fallback categorization for untracked exceptions.
	ErrUnknown ErrorCode = "UNKNOWN_ERROR"

	// XERR_FIELD_REQUIRED belongs to Group 1 (Presence & Nullity).
	// Targets missing parameters, empty payloads, or fields whose total absence matches an 'undefined' state.
	// Format expects: CTX, MSG, FIELD, [error]
	XERR_FIELD_REQUIRED = "[XERR_FIELD_REQUIRED]"

	// XERR_NIL_NOT_ALLOWED belongs to Group 1 (Presence & Nullity).
	// Targets cases where a field or reference pointer is explicitly supplied but contains a forbidden nil value.
	// Format expects: CTX, MSG, FIELD, [error]
	XERR_NIL_NOT_ALLOWED = "[XERR_NIL_NOT_ALLOWED]"

	// XERR_EMPTY_NOT_ALLOWED belongs to Group 1 (Presence & Nullity).
	// Targets fields that are allocated and non-nil, but their textual contents resolve to an empty string ("").
	// Format expects: CTX, MSG, FIELD, [error]
	XERR_EMPTY_NOT_ALLOWED = "[XERR_EMPTY_NOT_ALLOWED]"

	// XERR_ZERO_NOT_ALLOWED belongs to Group 1 (Presence & Nullity).
	// Targets scenarios where numeric primitives, lengths, or uninitialized value types resolve to a forbidden zero state (0).
	// Format expects: CTX, MSG, FIELD, [error]
	XERR_ZERO_NOT_ALLOWED = "[XERR_ZERO_NOT_ALLOWED]"

	// XERR_ALREADY_EXISTS belongs to Group 1 (Presence & Nullity).
	// Targets uniqueness constraint violations where a valid field value cannot be accepted because it duplicates an active record.
	// Format expects: CTX, MSG, FIELD, [error]
	XERR_ALREADY_EXISTS = "[XERR_ALREADY_EXISTS]"

	// XERR_NOT_FOUND belongs to Group 1 (Presence & Nullity).
	// Targets cases where a perfectly valid field lookup identifier fails to map to an active resource or file path.
	// Format expects: CTX, MSG, FIELD, TGT, [error]
	XERR_NOT_FOUND = "[XERR_NOT_FOUND]"

	// XERR_PERMISSION_DENIED belongs to Group 1 (Presence & Nullity).
	// Targets security contract breaches where the application lacks the OS credentials, RBAC tokens,
	// or read/write privileges required to interact with the target resource.
	// Format expects: CTX, MSG, FIELD, TGT, [error]
	XERR_PERMISSION_DENIED = "[XERR_PERMISSION_DENIED]"

	// XERR_RESOURCE_UNAVAILABLE belongs to Group 1 (Presence & Nullity).
	// Targets IO blockages, hardware failures, timeout sequences, or networking disruptions
	// that prevent communication with an otherwise structurally valid target endpoint or file stream.
	// Format expects: CTX, MSG, FIELD, TGT, [error]
	XERR_RESOURCE_UNAVAILABLE = "[XERR_RESOURCE_UNAVAILABLE]"

	// XERR_RESOURCE_CORRUPTED belongs to Group 1 (Presence & Nullity).
	// Targets integrity structural failures where the resource (file, payload, or state)
	// is physically present but its inner bytes break syntax rules, cryptographic checksums, or validation schemas.
	// Format expects: CTX, MSG, FIELD, TGT, [error]
	XERR_RESOURCE_CORRUPTED = "[XERR_RESOURCE_CORRUPTED]"

	// XERR_INVALID_VALUE belongs to Group 2 (Numeric & Boundaries).
	// General fallback for values that satisfy basic structural parsing but fail specialized domain business rules.
	// Format expects: CTX, MSG, FIELD, VALUE, RULES, [error]
	XERR_INVALID_VALUE = "[XERR_INVALID_VALUE]"

	// XERR_INVALID_VALUE_GT_ZERO belongs to Group 2 (Numeric & Boundaries).
	// Enforces that a evaluated mathematical property must be strictly greater than zero (> 0).
	// Format expects: CTX, MSG, FIELD, VALUE, RULES, [error]
	XERR_INVALID_VALUE_GT_ZERO = "[XERR_INVALID_VALUE_GT_ZERO]"

	// XERR_INVALID_VALUE_GE_ZERO belongs to Group 2 (Numeric & Boundaries).
	// Enforces that a evaluated mathematical property must be greater than or equal to zero (>= 0).
	// Format expects: CTX, MSG, FIELD, VALUE, RULES, [error]
	XERR_INVALID_VALUE_GE_ZERO = "[XERR_INVALID_VALUE_GE_ZERO]"

	// XERR_INVALID_VALUE_LT_ZERO belongs to Group 2 (Numeric & Boundaries).
	// Enforces that a evaluated mathematical property must be strictly less than zero (< 0).
	// Format expects: CTX, MSG, FIELD, VALUE, RULES, [error]
	XERR_INVALID_VALUE_LT_ZERO = "[XERR_INVALID_VALUE_LT_ZERO]"

	// XERR_INVALID_VALUE_LE_ZERO belongs to Group 2 (Numeric & Boundaries).
	// Enforces that a evaluated mathematical property must be less than or equal to zero (<= 0).
	// Format expects: CTX, MSG, FIELD, VALUE, RULES, [error]
	XERR_INVALID_VALUE_LE_ZERO = "[XERR_INVALID_VALUE_LE_ZERO]"

	// XERR_INVALID_VALUE_OUT_OF_RANGE belongs to Group 2 (Numeric & Boundaries).
	// Enforces that numbers, calendar dates, or generic offsets must stay enclosed within explicit low-high thresholds.
	// Format expects: CTX, MSG, FIELD, VALUE, RULES, [error]
	XERR_INVALID_VALUE_OUT_OF_RANGE = "[XERR_INVALID_VALUE_OUT_OF_RANGE]"

	// XERR_SELECTION_LIMIT_EXCEEDED belongs to Group 2 (Numeric & Boundaries).
	// Targets scenarios where the number of selected items breaks cardinality boundaries or exceeds the maximum quantity constraints.
	// Format expects: CTX, MSG, FIELD, OPT, COUNT, LIMIT, [error]
	XERR_SELECTION_LIMIT_EXCEEDED = "[XERR_SELECTION_LIMIT_EXCEEDED]"

	// XERR_INVALID_FORMAT belongs to Group 3 (Structure & Choices).
	// Targets syntax anomalies where string shapes break regex validations, structural encoding, or lexical requirements.
	// Format expects: CTX, MSG, FIELD, EXPECTED, GIVEN, [error]
	XERR_INVALID_FORMAT = "[XERR_INVALID_FORMAT]"

	XERR_MSG_INVALID_FORMAT_MARSHAL   = "marshal failed"
	XERR_MSG_INVALID_FORMAT_UNMARSHAL = "unmarshal failed"
	XERR_MSG_INVALID_FORMAT_PARSE     = "parse failed"

	// XERR_INVALID_TYPE belongs to Group 3 (Structure & Choices).
	// Targets type mismatch exceptions triggered during interface assertions, reflection mapping, or payload unmarshaling.
	// Format expects: CTX, MSG, FIELD, VALUE, EXPECTED_TYPE, [error]
	XERR_INVALID_TYPE = "[XERR_INVALID_TYPE]"

	// XERR_INVALID_OPTION belongs to Group 3 (Structure & Choices).
	// Targets invalid parameters outside a restrictive list of valid options or mutual exclusivity boundary contract violations.
	// Format expects: CTX, MSG, FIELD, OPT, OPTIONS, [error]
	XERR_INVALID_OPTION = "[XERR_INVALID_OPTION]"

	// XERR_MUTUAL_EXCLUSIVITY_VIOLATION belongs to Group 3 (Structure & Choices).
	// Targets structural contract breaches where choosing a specific field or option strictly invalidates the co-existence of others.
	// Format expects: CTX, MSG, FIELD, OPT, OPTIONS, [error]
	XERR_MUTUAL_EXCLUSIVITY_VIOLATION = "[XERR_MUTUAL_EXCLUSIVITY_VIOLATION]"

	// XERR_ASYMMETRIC_SIZES belongs to Group 3 (Structure & Choices).
	// Targets structural contract breaches where interdependent collections fail to match linear sequence lengths.
	// Format expects: CTX, MSG, FIELDS, [error]
	XERR_ASYMMETRIC_SIZES = "[XERR_ASYMMETRIC_SIZES]"

	// XERR_INVALID_DATA belongs to Group 4 (Generic Operational Fallbacks).
	// Standard layout fallback intended for wide operational dumps or key-value diagnostic pairs formatted via DataMsg.
	// Format expects: CTX, MSG, FIELD, DATA, [error]
	XERR_INVALID_DATA = "[XERR_INVALID_DATA]"
)

Variables

This section is empty.

Functions

func GetErrorMessage

func GetErrorMessage(code ErrorCode, errMap map[ErrorCode]string) string

GetErrorMessage returns the string message associated with the given ErrorCode from the provided map. If the code is not found in the map, it returns a generic unknown error fallback message.

func Log

func Log(
	ctx context.Context,
	targetErr error,
	customAttrs []slog.Attr,
	opts ...LogOption,
)

LogErr captures a detailed breakdown of the incoming error instance, converts its internal components into key-value structural attributes, merges external slog metadata tokens, and publishes a structured error stream via the standard library's slog ecosystem.

Unification strategy:

  • If 'targetErr' satisfies xerrors.DetailedError, it skips raw reflection overhead and extracts the pre-recorded component runtime frame path, code, and debugging data dumps.
  • If 'targetErr' is a standard Go generic error, it evaluates runtime.Caller backtraces as a fallback parsing layout sequence to locate the failure context.

func MsgArraySize

func MsgArraySize(args ...any) string

MsgArraySize processes a variadic sequence of alternating key-length arguments and builds a unified diagnostic string mapping collections to their dimensions.

Arguments must follow a strict sequential layout: string (name) paired with an integer (size). Numeric zeros (0) are explicitly preserved as they represent critical operational states.

func MsgData

func MsgData(args ...any) string

MsgData processes a variadic sequence of alternating key-value arguments and stringifies them into a highly predictable, comma-separated operational layout (e.g., "key1=val1, key2=val2").

Exclusion Mechanics:

  • By default, it completely omits any pair where the VALUE resolves to nil, zero (0), or an empty string ("").
  • If the very first argument is provided as a []any slice, it overrides the default value blacklist, enforcing only the elements specified within that slice as the new filtration parameters.

func MsgOptions

func MsgOptions(args ...any) string

MsgOptions aggregates a variadic sequence of arguments into a clean, comma-separated text representation where strings and complex types are dynamically enclosed in single quotes.

Exclusion Mechanics:

  • By default, it ignores explicit nil values, zeros (0), and empty strings ("") to prevent visual clutter.
  • If the very first argument is provided as a []any slice, it overrides the default exclusion rule.

func NewErr

func NewErr(message string, args ...any) error

NewErr acts as a lightweight, polymorphic factory that creates and returns a standard Go error instance. It features an advanced internal normalization engine tailored for the corporate layout triggered by the XERR token. If the incoming message matches XERR, it dynamically reconstructs the structural string output based on the number of arguments provided, automatically backfilling missing slots with the empty set marker "ø". NewErr acts as a lightweight, polymorphic factory that creates and returns a standard Go error instance. It intercepts specialized corporate XERR_ tokens to dynamically delegate the formatting sequence to dedicated underlying layout builder functions.

func Print

func Print(err error)

Print writes the error's string representation directly to the standard error stream (os.Stderr). It acts as a lightweight, zero-allocation wrapper around fmt.Fprintln, providing a swift debugging mechanism that bypasses context allocations or structured logging handler configurations. If the incoming error target is nil, the execution block returns early without writing to the stream.

Types

type DetailedError

type DetailedError interface {
	// Code returns the categorical string constant domain mapping for this failure event.
	Code() ErrorCode

	// Component pinpoints the specific architectural layer or tracking package path.
	Component() string

	// error ensures native alignment with Go standard library errors handling semantics.
	error

	// WithCallerSkip allows dynamically adjusting the runtime stack frame skip level to recompute
	// the component identifier. This is essential when NewError is wrapped inside custom factory
	// utilities or logging helper blocks, ensuring the framework pinpoints the true origin of the failure.
	// It returns the updated DetailedError to support fluent API call chaining.
	WithCallerSkip(skip int) DetailedError

	// Message returns the readable operational summary describing what went wrong.
	Message() string

	// Data returns raw debugging contexts such as data dumps or corrupted payloads.
	Data() string

	// DebugError computes a highly readable formatted diagnostic block string ready for loggers or consoles.
	DebugError() string
}

DetailedError standardizes the functional execution capabilities required to manage rich, decoupled diagnostic payloads across network borders, microservices, and system boundaries.

func NewError

func NewError(
	code ErrorCode,
	err error,
	message string,
	data string,
) DetailedError

NewError initializes a rich DetailedError instance. It pre-configures a default call stack frame skip level but postpones the actual heavy runtime inspection until the component property is explicitly requested by a logger or console channel.

type Error

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

Error provides a concrete structural implementation of the DetailedError interface. It encapsulates contextual metadata alongside standard system exceptions to maximize observability and reduce cognitive friction during troubleshooting pipelines.

func (*Error) Code

func (e *Error) Code() ErrorCode

Code retrieves the structured domain classification assigned to this error.

func (*Error) Component

func (e *Error) Component() string

Component returns the dynamically reflected runtime namespace where the failure originated. It leverages lazy-loading evaluation, executing stack inspection only upon the first request.

func (*Error) Data

func (e *Error) Data() string

Data fetches the secondary raw context strings attached to this structural payload container.

func (*Error) DebugError

func (e *Error) DebugError() string

DebugError returns a multi-line diagnostic report containing comprehensive internal tracking metadata.

func (*Error) Error

func (e *Error) Error() string

Error satisfies the standard Go library errors handling interface contract specification. It builds a summarized formatted diagnostic feedback sequence.

func (*Error) Message

func (e *Error) Message() string

Message extracts the human-readable summary detailing the specific breakdown event.

func (*Error) WithCallerSkip

func (e *Error) WithCallerSkip(skip int) DetailedError

WithCallerSkip allows dynamically adjusting the runtime stack frame skip level. This resetting behavior automatically clears any previously loaded component metadata state, forcing the runtime analyzer to re-evaluate call origins on subsequent property calls.

type ErrorCode

type ErrorCode string

ErrorCode defines a domain-specific string representation for error classification.

type LogOption

type LogOption func(*logConfig)

LogOption defines the functional option signature used to configure the behavior of structured error logging.

func WithLogCallerSkip

func WithLogCallerSkip(skip int) LogOption

WithLogCallerSkip dynamically adjusts the runtime.Caller frame interception level during raw error fallbacks. Pass a positive integer (e.g., 1) if this function is wrapped inside another downstream corporate logging utility.

Jump to

Keyboard shortcuts

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