errmgr

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 6, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package errmgr provides common error definitions and categories for use across applications. These predefined errors are designed for consistency in error handling and can be used directly as immutable instances or copied for customization using Copy().

Package errmgr provides functionality for managing error templates, counts, thresholds, and alerts in a thread-safe manner, building on the core errors package.

Package errmgr provides error monitoring functionality.

Index

Constants

View Source
const (
	CategoryAuth       errors.ErrorCategory = "auth"       // Authentication-related errors (e.g., login failures)
	CategoryBusiness   errors.ErrorCategory = "business"   // Business logic errors (e.g., rule violations)
	CategoryDatabase   errors.ErrorCategory = "database"   // Database-related errors (e.g., connection issues)
	CategoryIO         errors.ErrorCategory = "io"         // Input/Output-related errors (e.g., file operations)
	CategoryNetwork    errors.ErrorCategory = "network"    // Network-related errors (e.g., timeouts, unreachable hosts)
	CategorySystem     errors.ErrorCategory = "system"     // System-level errors (e.g., resource exhaustion)
	CategoryUser       errors.ErrorCategory = "user"       // User-related errors (e.g., invalid input, permissions)
	CategoryValidation errors.ErrorCategory = "validation" // Validation-related errors (e.g., invalid input formats)
)

Common error categories used for organizing errors across different domains.

View Source
const (
	CodeBadRequest         = 400 // HTTP 400 Bad Request (client error, invalid input)
	CodeUnauthorized       = 401 // HTTP 401 Unauthorized (authentication required)
	CodeForbidden          = 403 // HTTP 403 Forbidden (access denied)
	CodeNotFound           = 404 // HTTP 404 Not Found (resource not found)
	CodeMethodNotAllowed   = 405 // HTTP 405 Method Not Allowed (unsupported method)
	CodeConflict           = 409 // HTTP 409 Conflict (resource conflict)
	CodeUnprocessable      = 422 // HTTP 422 Unprocessable Entity (semantic errors in request)
	CodeTooManyRequests    = 429 // HTTP 429 Too Many Requests (rate limiting)
	CodeInternalError      = 500 // HTTP 500 Internal Server Error (server failure)
	CodeNotImplemented     = 501 // HTTP 501 Not Implemented (feature not supported)
	CodeServiceUnavailable = 503 // HTTP 503 Service Unavailable (temporary unavailability)
)

Common HTTP status codes used for error responses, aligned with REST API conventions.

Variables

View Source
var (
	ErrInvalidArg         = errors.New("invalid argument").WithCode(CodeBadRequest)
	ErrNotFound           = errors.New("not found").WithCode(CodeNotFound)
	ErrPermission         = errors.New("permission denied").WithCode(CodeForbidden)
	ErrTimeout            = errors.New("operation timed out").WithTimeout()
	ErrUnknown            = errors.New("unknown error").WithCode(CodeInternalError)
	ErrDBConnRetryable    = errors.New("database connection failed").WithCategory(CategoryDatabase).WithRetryable()
	ErrNetworkRetryable   = errors.New("network failure").WithCategory(CategoryNetwork).WithRetryable()
	ErrNetworkTimedOut    = errors.New("network timeout").WithCategory(CategoryNetwork).WithTimeout().WithRetryable()
	ErrServiceRetryable   = errors.New("service unavailable").WithCode(CodeServiceUnavailable).WithRetryable()
	ErrRateLimitRetryable = errors.New("rate limit exceeded").WithCode(CodeTooManyRequests).WithRetryable()
)

Generic Predefined Errors (Static) These are immutable instances suitable for direct use or copying with Copy(). Errors requiring specific properties like WithRetryable() or WithTimeout() are defined here.

View Source
var (
	ErrAuthFailed   = Coded("ErrAuthFailed", "authentication failed for %s: %s", CodeUnauthorized)
	ErrInvalidToken = Coded("ErrInvalidToken", "invalid authentication token: %s", CodeUnauthorized)
	ErrMissingCreds = Coded("ErrMissingCreds", "missing credentials: %s", CodeBadRequest)
	ErrTokenExpired = Coded("ErrTokenExpired", "authentication token expired: %s", CodeUnauthorized)
)

Authentication Errors (Templated) Use these by providing arguments, e.g., ErrAuthFailed("user@example.com", "invalid password").

View Source
var (
	ErrBusinessRule      = Categorized(CategoryBusiness, "ErrBusinessRule", "business rule violation: %s")
	ErrInsufficientFunds = Categorized(CategoryBusiness, "ErrInsufficientFunds", "insufficient funds: %s")
)

Business Logic Errors (Templated) Example: ErrInsufficientFunds("account123", "balance too low").

View Source
var (
	ErrDBConnection = Categorized(CategoryDatabase, "ErrDBConnection", "database connection failed: %s")
	ErrDBConstraint = Coded("ErrDBConstraint", "database constraint violation: %s", CodeConflict)
	ErrDBQuery      = Categorized(CategoryDatabase, "ErrDBQuery", "database query failed: %s")
	ErrDBTimeout    = Categorized(CategoryDatabase, "ErrDBTimeout", "database operation timed out: %s")
)

Database Errors (Templated) Example: ErrDBConnection("mysql", "host unreachable").

View Source
var (
	ErrFileNotFound = Coded("ErrFileNotFound", "file (%s) not found", CodeNotFound)
	ErrIORead       = Categorized(CategoryIO, "ErrIORead", "I/O read error: %s")
	ErrIOWrite      = Categorized(CategoryIO, "ErrIOWrite", "I/O write error: %s")
)

IO Errors (Templated) Example: ErrFileNotFound("/path/to/file").

View Source
var (
	ErrNetworkConnRefused = Categorized(CategoryNetwork, "ErrNetworkConnRefused", "connection refused: %s")
	ErrNetworkTimeout     = Categorized(CategoryNetwork, "ErrNetworkTimeout", "network timeout: %s")
	ErrNetworkUnreachable = Categorized(CategoryNetwork, "ErrNetworkUnreachable", "network unreachable: %s")
)

Network Errors (Templated) Example: ErrNetworkTimeout("http://example.com", "no response").

View Source
var (
	ErrConfigInvalid     = Coded("ErrConfigInvalid", "invalid configuration: %s", CodeInternalError)
	ErrResourceExhausted = Coded("ErrResourceExhausted", "resource exhausted: %s", CodeServiceUnavailable)
	ErrSystemFailure     = Coded("ErrSystemFailure", "system failure: %s", CodeInternalError)
	ErrSystemUnhealthy   = Coded("ErrSystemUnhealthy", "system unhealthy: %s", CodeServiceUnavailable)
)

System Errors (Templated) Example: ErrResourceExhausted("memory", "out of memory").

View Source
var (
	ErrUserLocked     = Coded("ErrUserLocked", "user %s is locked: %s", CodeForbidden)
	ErrUserNotFound   = Coded("ErrUserNotFound", "user %s not found: %s", CodeNotFound)
	ErrUserPermission = Coded("ErrUserPermission", "user %s lacks permission: %s", CodeForbidden)
	ErrUserSuspended  = Coded("ErrUserSuspended", "user %s is suspended: %s", CodeForbidden)
)

User Errors (Templated) Example: ErrUserNotFound("user123", "not in database").

View Source
var (
	ErrInvalidFormat    = Coded("ErrInvalidFormat", "invalid format: %s", CodeBadRequest)
	ErrValidationFailed = Coded("ErrValidationFailed", "validation failed: %s", CodeBadRequest)
)

Validation Errors (Templated) Example: ErrValidationFailed("email", "invalid email format").

View Source
var (
	ErrConflict           = Coded("ErrConflict", "conflict occurred: %s", CodeConflict)
	ErrMethodNotAllowed   = Coded("ErrMethodNotAllowed", "method %s not allowed", CodeMethodNotAllowed)
	ErrNotImplemented     = Coded("ErrNotImplemented", "%s not implemented", CodeNotImplemented)
	ErrRateLimitExceeded  = Coded("ErrRateLimitExceeded", "rate limit exceeded: %s", CodeTooManyRequests)
	ErrServiceUnavailable = Coded("ErrServiceUnavailable", "service (%s) unavailable", CodeServiceUnavailable)
	ErrUnprocessable      = Coded("ErrUnprocessable", "unprocessable entity: %s", CodeUnprocessable)
)

Additional REST API Errors (Templated) Example: ErrMethodNotAllowed("POST", "only GET allowed").

View Source
var (
	ErrDeserialization      = Define("ErrDeserialization", "deserialization error: %s")
	ErrExternalService      = Define("ErrExternalService", "external service (%s) error")
	ErrSerialization        = Define("ErrSerialization", "serialization error: %s")
	ErrUnsupportedOperation = Coded("ErrUnsupportedOperation", "unsupported operation %s", CodeNotImplemented)
)

Additional Domain-Specific Errors (Templated) Example: ErrSerialization("json", "invalid data").

View Source
var (
	AuthFailed      = Categorized(CategoryAuth, "AuthFailed", "authentication failed for %s: %s")
	BusinessError   = Categorized(CategoryBusiness, "BusinessError", "business error: %s")
	DBError         = Categorized(CategoryDatabase, "DBError", "database error: %s")
	IOError         = Categorized(CategoryIO, "IOError", "I/O error: %s")
	NetworkError    = Categorized(CategoryNetwork, "NetworkError", "network failure: %s")
	SystemError     = Categorized(CategorySystem, "SystemError", "system error: %s")
	UserError       = Categorized(CategoryUser, "UserError", "user error: %s")
	ValidationError = Categorized(CategoryValidation, "ValidationError", "validation error: %s")
)

Predefined Templates with Categories (Templated) These are convenience wrappers with categories applied; use like AuthFailed("user", "reason").

Functions

func Categorized

func Categorized(category errors.ErrorCategory, name, template string) func(...interface{}) *errors.Error

Categorized creates a categorized error template and returns a function to create errors. The returned function applies the category to each error instance.

func CloseMonitor

func CloseMonitor(name string)

CloseMonitor closes the alert channel for a specific error name. Thread-safe; subsequent alerts for this name are ignored.

func Coded

func Coded(name, template string, code int) func(...interface{}) *errors.Error

Coded creates a templated error with a specific HTTP status code. It wraps Define and applies the code to each error instance returned.

func Configure

func Configure(cfg Config)

Configure updates the global configuration for the errmgr package. Thread-safe; applies immediately to all subsequent operations.

func Copy

func Copy(err *errors.Error) *errors.Error

Copy creates a new instance of a predefined static error, ensuring immutability of originals. Use this for static errors; templated errors should be called directly with arguments.

func Define

func Define(name, template string) func(...interface{}) *errors.Error

Define creates a templated error that formats a message with provided arguments. The error is tracked in the registry if error management is enabled.

func GetThreshold

func GetThreshold(name string) (uint64, bool)

GetThreshold returns the current threshold for an error name, if set. Returns 0 and false if no threshold is defined.

func Metrics

func Metrics() map[string]uint64

Metrics returns a snapshot of error counts for monitoring systems. Returns nil if error management is disabled or no counts exist.

func RemoveThreshold

func RemoveThreshold(name string)

RemoveThreshold removes the threshold for a specific error name. Thread-safe; no effect if no threshold exists.

func Reset

func Reset()

Reset clears all counters and removes their registrations. Has no effect if error management is disabled.

func ResetCounter

func ResetCounter(name string)

ResetCounter resets the occurrence counter for a specific error type. Has no effect if error management is disabled or the name isn’t registered.

func SetThreshold

func SetThreshold(name string, threshold uint64)

SetThreshold sets a count threshold for an error name, triggering alerts when exceeded. Alerts are sent to the Monitor channel if one exists for the name.

func Tracked

func Tracked(name string, fn func(...interface{}) *errors.Error) func(...interface{}) *errors.Error

Tracked registers a custom error function and tracks its occurrences in the registry. The returned function increments the error count each time it is called.

Types

type Config

type Config struct {
	DisableMetrics bool // Disables counting and tracking if true
}

Config holds configuration for the errmgr package.

type Monitor

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

Monitor represents an error monitoring channel for a specific error name. It receives alerts when the error count exceeds a configured threshold set via SetThreshold.

func NewMonitor

func NewMonitor(name string) *Monitor

NewMonitor creates a new Monitor for the given error name with a default buffer of 10. Reuses an existing channel if one is already registered; thread-safe. Use NewMonitorBuffered for a custom buffer size.

func NewMonitorBuffered

func NewMonitorBuffered(name string, buffer int) *Monitor

NewMonitorBuffered creates a new Monitor for the given error name with a specified buffer size. Reuses an existing channel if one is already registered; thread-safe. Buffer must be non-negative (0 means unbuffered); use NewMonitor for the default buffer of 10.

func (*Monitor) Alerts

func (m *Monitor) Alerts() <-chan *errors.Error

Alerts returns the channel for receiving error alerts. Alerts are sent when the error count exceeds the threshold set by SetThreshold. Returns nil if the monitor has been closed.

func (*Monitor) Close

func (m *Monitor) Close()

Close shuts down the monitor channel and removes it from the registry. Thread-safe and idempotent; subsequent calls have no effect.

func (*Monitor) IsClosed

func (m *Monitor) IsClosed() bool

IsClosed reports whether the monitor’s channel has been closed. Thread-safe; useful for checking monitor status before use.

Jump to

Keyboard shortcuts

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