errors

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package errors provides error types, sentinel errors, and error wrapping utilities for the mono-framework. This package can be safely imported by both pkg/mono and internal packages without creating import cycles.

Index

Examples

Constants

View Source
const (
	// ServiceSubjectPattern defines the pattern for service subjects
	ServiceSubjectPattern = "services.<module>.<service>"

	// EventSubjectPattern defines the pattern for event subjects
	EventSubjectPattern = "events.[<module>.]<domain>.[<sub-domain>].<event-type>"

	// ReservedPrefix is the reserved subject prefix for framework internal use
	ReservedPrefix = "_mono."
)

Subject naming patterns

Variables

View Source
var (
	// ErrModuleNotFound is returned when a module is not registered
	ErrModuleNotFound = errors.New("module not found")

	// ErrServiceNotFound is returned when a service is not registered
	ErrServiceNotFound = errors.New("service not found")

	// ErrModuleAlreadyRegistered is returned when attempting to register a duplicate module
	ErrModuleAlreadyRegistered = errors.New("module already registered")

	// ErrServiceAlreadyRegistered is returned when attempting to register a duplicate service
	ErrServiceAlreadyRegistered = errors.New("service already registered")

	// ErrCircularDependency is returned when a circular dependency is detected
	ErrCircularDependency = errors.New("circular dependency detected")

	// ErrMissingDependency is returned when a required dependency is not registered
	ErrMissingDependency = errors.New("missing dependency")

	// ErrServiceUnavailable is returned when a service is temporarily unavailable
	ErrServiceUnavailable = errors.New("service unavailable")

	// ErrInvalidConfiguration is returned when configuration validation fails
	ErrInvalidConfiguration = errors.New("invalid configuration")

	// ErrModuleStartFailed is returned when a module fails to start
	ErrModuleStartFailed = errors.New("module start failed")

	// ErrModuleStopFailed is returned when a module fails to stop
	ErrModuleStopFailed = errors.New("module stop failed")

	// ErrModulePanic is returned when a module panics during lifecycle operations
	ErrModulePanic = errors.New("module panic")

	// ErrContainerNotBound is returned when ServiceContainer is not bound to a module
	ErrContainerNotBound = errors.New("container not bound to module")

	// ErrPluginNotFound is returned when a plugin alias is not registered
	ErrPluginNotFound = errors.New("plugin not found")

	// ErrPluginAlreadyRegistered is returned when attempting to register a duplicate plugin alias
	ErrPluginAlreadyRegistered = errors.New("plugin already registered")
)

Sentinel errors for common error cases

Functions

func AggregateErrors

func AggregateErrors(errs []error) error

AggregateErrors aggregates an array of errors into a single error. Returns nil if the array is empty or all errors are nil.

Example

ExampleAggregateErrors demonstrates combining multiple errors.

package main

import (
	"errors"
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	errs := []error{
		errors.New("first error"),
		nil, // nil errors are filtered out
		errors.New("second error"),
	}

	combined := monoerrors.AggregateErrors(errs)
	if combined != nil {
		fmt.Println("Errors were aggregated")
	}
}
Output:
Errors were aggregated
Example (SingleError)

ExampleAggregateErrors_singleError demonstrates that single errors are returned as-is.

package main

import (
	"errors"
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	errs := []error{
		nil,
		errors.New("only error"),
		nil,
	}

	combined := monoerrors.AggregateErrors(errs)
	fmt.Println(combined.Error())
}
Output:
only error

func CheckSubjectConflict

func CheckSubjectConflict(serviceSubjects, eventSubjects []string) []string

CheckSubjectConflict checks if a subject might conflict between services and events.

This function logs warnings for subjects that could cause routing confusion. For example, "services.user.created" vs "events.user.created" might be confusing.

Returns true if a potential conflict is detected (same module/domain and service/event names).

func FormatDependencyChain

func FormatDependencyChain(chain []string) string

FormatDependencyChain formats a dependency chain for display.

Example

ExampleFormatDependencyChain demonstrates formatting dependency chains.

package main

import (
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	chain := []string{"auth", "user", "notification"}
	formatted := monoerrors.FormatDependencyChain(chain)

	fmt.Println(formatted)
}
Output:
auth -> user -> notification

func FormatFrameworkState

func FormatFrameworkState(state types.MonoFrameworkState) string

FormatFrameworkState formats a MonoFrameworkState for display.

func IsConfigurationError

func IsConfigurationError(err error) bool

IsConfigurationError reports whether err is a ConfigurationError.

Example

ExampleIsConfigurationError demonstrates checking for configuration errors.

package main

import (
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	err := monoerrors.WrapInvalidConfiguration(1, "WithNATSPort", -1, "port must be positive")

	if monoerrors.IsConfigurationError(err) {
		fmt.Println("This is a configuration error")
	}
}
Output:
This is a configuration error

func IsDependencyError

func IsDependencyError(err error) bool

IsDependencyError reports whether err is a DependencyError.

Example

ExampleIsDependencyError demonstrates checking for dependency errors.

package main

import (
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	err := monoerrors.WrapMissingDependency("order-module", "payment-module")

	if monoerrors.IsDependencyError(err) {
		fmt.Println("This is a dependency error")
	}
}
Output:
This is a dependency error

func IsEventStreamError

func IsEventStreamError(err error) bool

IsEventStreamError reports whether err is an EventStreamError.

func IsKebabCase

func IsKebabCase(token string) bool

IsKebabCase is the exported version of isKebabCase for testing. It checks if a token follows kebab-case convention.

func IsModuleError

func IsModuleError(err error) bool

IsModuleError reports whether err is a ModuleError.

Example

ExampleIsModuleError demonstrates checking for module errors.

package main

import (
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	err := monoerrors.WrapModuleNotFound("unknown-module")

	if monoerrors.IsModuleError(err) {
		fmt.Println("This is a module error")
	}
}
Output:
This is a module error

func IsRemoteError added in v0.0.3

func IsRemoteError(err error) bool

IsRemoteError reports whether err is a RemoteError.

func IsServiceError

func IsServiceError(err error) bool

IsServiceError reports whether err is a ServiceError.

Example

ExampleIsServiceError demonstrates checking for service errors.

package main

import (
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	err := monoerrors.WrapServiceNotFound("payment-processor", "payment")

	if monoerrors.IsServiceError(err) {
		fmt.Println("This is a service error")
	}
}
Output:
This is a service error

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError reports whether err is a TimeoutError.

func ValidateEventDefinitionSubject

func ValidateEventDefinitionSubject(subject string) error

ValidateEventDefinitionSubject validates an event subject for event definitions.

Event subjects must match: events.[<module>.]<domain>.[<sub-domain>].<event-type> All tokens must be kebab-case. Wildcards (*,>) are NOT allowed for event definitions.

func ValidateEventSubscriberSubject

func ValidateEventSubscriberSubject(subject string) error

ValidateEventSubscriberSubject validates an event subject to be used by subscribers.

Event subjects must match: events.[<module>.]<domain>.[<sub-domain>].<event-type> All tokens must be kebab-case. Wildcards (*,>) allowed for subscriptions.

func ValidateServiceSubject

func ValidateServiceSubject(subject string) error

ValidateServiceSubject validates a service subject.

Service subjects must match: services.<module>.<service> All tokens must be kebab-case with no wildcards.

func WrapCircularDependency

func WrapCircularDependency(chain []string) error

WrapCircularDependency wraps ErrCircularDependency with dependency chain context.

Example

ExampleWrapCircularDependency demonstrates wrapping circular dependency errors.

package main

import (
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	chain := []string{"module-a", "module-b", "module-c", "module-a"}
	err := monoerrors.WrapCircularDependency(chain)

	fmt.Println("Error detected:", monoerrors.IsDependencyError(err))
}
Output:
Error detected: true

func WrapEventStreamError

func WrapEventStreamError(streamName, subject, operation string, err error) error

WrapEventStreamError wraps an error with event stream context. Use this when a JetStream operation fails and you have stream/subject information.

func WrapEventStreamNotAvailable

func WrapEventStreamNotAvailable(subject, operation string, err error) error

WrapEventStreamNotAvailable wraps an error indicating event stream is not available. This is typically used when publishing to a subject that has no configured stream, meaning messages cannot be persisted. Similar to "no responders" but for streams.

func WrapInvalidConfiguration

func WrapInvalidConfiguration(optionIndex int, optionName string, value any, reason string) error

WrapInvalidConfiguration wraps ErrInvalidConfiguration with configuration context.

func WrapInvalidModule

func WrapInvalidModule(module types.Module, reason string) error

WrapInvalidModule wraps an error indicating an invalid module.

func WrapMissingDependency

func WrapMissingDependency(module, dependency string) error

WrapMissingDependency wraps ErrMissingDependency with dependency context.

func WrapModuleAlreadyRegistered

func WrapModuleAlreadyRegistered(moduleName string) error

WrapModuleAlreadyRegistered wraps ErrModuleAlreadyRegistered with module context.

func WrapModuleNotFound

func WrapModuleNotFound(moduleName string) error

WrapModuleNotFound wraps ErrModuleNotFound with module context.

func WrapModulePanic

func WrapModulePanic(moduleName, operation string, panicValue any) error

WrapModulePanic wraps panic recovery with module context.

func WrapModuleStartFailed

func WrapModuleStartFailed(moduleName string, err error) error

WrapModuleStartFailed wraps module start failures with context.

func WrapModuleStopFailed

func WrapModuleStopFailed(moduleName string, err error) error

WrapModuleStopFailed wraps module stop failures with context.

func WrapPluginAlreadyRegistered

func WrapPluginAlreadyRegistered(alias string) error

WrapPluginAlreadyRegistered wraps ErrPluginAlreadyRegistered with plugin alias context.

func WrapPluginNotFound

func WrapPluginNotFound(alias string) error

WrapPluginNotFound wraps ErrPluginNotFound with plugin alias context.

func WrapPluginStartFailed

func WrapPluginStartFailed(alias string, err error) error

WrapPluginStartFailed wraps plugin start failures with context.

func WrapPluginStopFailed

func WrapPluginStopFailed(alias string, err error) error

WrapPluginStopFailed wraps plugin stop failures with context.

func WrapRemoteError added in v0.0.3

func WrapRemoteError(serviceName, moduleName, message, errorType string) error

WrapRemoteError creates a new RemoteError from response headers. This is used to wrap errors received from remote RequestReply service handlers.

func WrapServiceAlreadyRegistered

func WrapServiceAlreadyRegistered(serviceName, moduleName string, serviceType types.ServiceType) error

WrapServiceAlreadyRegistered wraps ErrServiceAlreadyRegistered with service context.

func WrapServiceError

func WrapServiceError(serviceName, moduleName string, serviceType types.ServiceType, err error) error

WrapServiceError wraps an error with service context.

func WrapServiceNotFound

func WrapServiceNotFound(serviceName, moduleName string) error

WrapServiceNotFound wraps ErrServiceNotFound with service context.

func WrapServiceUnavailable

func WrapServiceUnavailable(serviceName, moduleName string, serviceType types.ServiceType, err error) error

WrapServiceUnavailable wraps ErrServiceUnavailable with service context and explicit service type.

func WrapTimeout

func WrapTimeout(operation string, duration time.Duration, err error) error

WrapTimeout wraps an error and creates a new TimeoutError with the given context.

Types

type ConfigurationError

type ConfigurationError struct {
	OptionIndex int
	OptionName  string
	Value       any
	Err         error
}

ConfigurationError wraps errors with configuration context. It provides option index, option name, and value information for debugging.

func GetConfigurationError

func GetConfigurationError(err error) (*ConfigurationError, bool)

GetConfigurationError extracts ConfigurationError from err if present.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

Error implements the error interface.

func (*ConfigurationError) Unwrap

func (e *ConfigurationError) Unwrap() error

Unwrap returns the wrapped error.

type DependencyError

type DependencyError struct {
	Module     string
	Dependency string
	Chain      []string
	Err        error
}

DependencyError wraps errors with dependency chain context. It provides module, dependency, and chain information for debugging circular dependencies.

func (*DependencyError) Error

func (e *DependencyError) Error() string

Error implements the error interface.

func (*DependencyError) Unwrap

func (e *DependencyError) Unwrap() error

Unwrap returns the wrapped error.

type EventStreamError

type EventStreamError struct {
	StreamName string
	Subject    string
	Operation  string
	Err        error
}

EventStreamError wraps errors with event stream context. It provides stream name, subject, and operation information for debugging stream errors. This error type is specifically for JetStream operations where messages need to be persisted but the stream is not configured or unavailable.

func GetEventStreamError

func GetEventStreamError(err error) (*EventStreamError, bool)

GetEventStreamError extracts EventStreamError from err if present.

func (*EventStreamError) Error

func (e *EventStreamError) Error() string

Error implements the error interface.

func (*EventStreamError) Unwrap

func (e *EventStreamError) Unwrap() error

Unwrap returns the wrapped error.

type ModuleError

type ModuleError struct {
	ModuleName string
	Operation  string
	Err        error
}

ModuleError wraps errors with module context. It provides module name and operation information for debugging.

func (*ModuleError) Error

func (e *ModuleError) Error() string

Error implements the error interface.

func (*ModuleError) Unwrap

func (e *ModuleError) Unwrap() error

Unwrap returns the wrapped error.

type RemoteError added in v0.0.3

type RemoteError struct {
	Message     string
	ServiceName string
	ModuleName  string
	ErrorType   string
}

RemoteError represents an error returned from a remote service call. It wraps errors that were propagated back from RequestReply handlers. This error type indicates the error originated from a remote service, not from local code or network issues.

func GetRemoteError added in v0.0.3

func GetRemoteError(err error) (*RemoteError, bool)

GetRemoteError extracts RemoteError from err if present.

func (*RemoteError) Error added in v0.0.3

func (e *RemoteError) Error() string

Error implements the error interface.

func (*RemoteError) Unwrap added in v0.0.3

func (e *RemoteError) Unwrap() error

Unwrap returns nil as RemoteError is a terminal error. This method exists for consistency with other error types in the package.

type ServiceError

type ServiceError struct {
	ServiceName string
	ModuleName  string
	ServiceType types.ServiceType
	Err         error
}

ServiceError wraps errors with service context. It provides service name, module name, and service type information.

func GetServiceError

func GetServiceError(err error) (*ServiceError, bool)

GetServiceError extracts ServiceError from err if present.

Example

ExampleGetServiceError demonstrates extracting service error details.

package main

import (
	"fmt"

	monoerrors "github.com/go-monolith/mono/pkg/errors"
)

func main() {
	err := monoerrors.WrapServiceNotFound("my-service", "my-module")

	serviceErr, ok := monoerrors.GetServiceError(err)
	if ok {
		fmt.Println("Service:", serviceErr.ServiceName)
		fmt.Println("Module:", serviceErr.ModuleName)
	}
}
Output:
Service: my-service
Module: my-module

func (*ServiceError) Error

func (e *ServiceError) Error() string

Error implements the error interface.

func (*ServiceError) Unwrap

func (e *ServiceError) Unwrap() error

Unwrap returns the wrapped error.

type SubjectType

type SubjectType int

SubjectType represents the type of NATS subject

const (
	// SubjectTypeService indicates a service subject
	SubjectTypeService SubjectType = iota

	// SubjectTypeEvent indicates an event subject
	SubjectTypeEvent

	// SubjectTypeUnknown indicates an unknown subject type
	SubjectTypeUnknown
)

func ValidateSubject

func ValidateSubject(subject string, allowWildcard bool) (SubjectType, error)

ValidateSubject validates a NATS subject against naming conventions.

Subject naming rules:

  • Service subjects: services.<module>.<service>
  • Event subjects: events.<domain>.<event-type>
  • All tokens must be kebab-case (lowercase, numbers, hyphens)
  • Reserved prefix "_mono." is not allowed for user subjects
  • Wildcards (*,>) only allowed in event subjects for subscriptions

Returns the subject type and an error if validation fails.

type TimeoutError

type TimeoutError struct {
	Operation string
	Duration  time.Duration
	Err       error
}

TimeoutError wraps errors with timeout context. It provides operation and duration information for debugging timeouts.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface.

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Timeout reports whether this error represents a timeout.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap returns the wrapped error.

Jump to

Keyboard shortcuts

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