errors

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Is

func Is(err error, code ErrorCode) bool

Is checks if error matches specific error code

Types

type Error

type Error struct {
	Code       ErrorCode              `json:"code"`
	Message    string                 `json:"message"`
	Details    map[string]interface{} `json:"details,omitempty"`
	Severity   ErrorSeverity          `json:"severity"`
	Timestamp  time.Time              `json:"timestamp"`
	RequestID  string                 `json:"request_id,omitempty"`
	UserID     string                 `json:"user_id,omitempty"`
	TenantID   string                 `json:"tenant_id,omitempty"`
	StackTrace []string               `json:"stack_trace,omitempty"`
	Cause      error                  `json:"-"`
}

Error represents a structured error

func BadRequest

func BadRequest(message string) *Error

BadRequest creates a bad request error

func Forbidden

func Forbidden(message string) *Error

Forbidden creates a forbidden error

func Internal

func Internal(message string) *Error

Internal creates an internal server error

func Internalf

func Internalf(format string, args ...interface{}) *Error

Internalf creates an internal server error with formatted message

func New

func New(code ErrorCode, message string) *Error

New creates a new error

func Newf

func Newf(code ErrorCode, format string, args ...interface{}) *Error

Newf creates a new error with formatted message

func NotFound

func NotFound(message string) *Error

NotFound creates a not found error

func Unauthorized

func Unauthorized(message string) *Error

Unauthorized creates an unauthorized error

func Validation

func Validation(message string) *Error

Validation creates a validation error

func Wrap

func Wrap(err error, code ErrorCode, message string) *Error

Wrap wraps an existing error with additional context

func Wrapf

func Wrapf(err error, code ErrorCode, format string, args ...interface{}) *Error

Wrapf wraps an existing error with formatted message

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

func (*Error) HTTPStatus

func (e *Error) HTTPStatus() int

HTTPStatus returns appropriate HTTP status code

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause sets the underlying cause

func (*Error) WithDetail

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

WithDetail adds a detail to the error

func (*Error) WithRequestID

func (e *Error) WithRequestID(requestID string) *Error

WithRequestID sets the request ID

func (*Error) WithStackTrace

func (e *Error) WithStackTrace() *Error

WithStackTrace adds stack trace

func (*Error) WithTenantID

func (e *Error) WithTenantID(tenantID string) *Error

WithTenantID sets the tenant ID

func (*Error) WithUserID

func (e *Error) WithUserID(userID string) *Error

WithUserID sets the user ID

type ErrorCode

type ErrorCode string

ErrorCode represents standardized error codes

const (
	// General errors
	ErrCodeInternal     ErrorCode = "INTERNAL_ERROR"
	ErrCodeNotFound     ErrorCode = "NOT_FOUND"
	ErrCodeBadRequest   ErrorCode = "BAD_REQUEST"
	ErrCodeUnauthorized ErrorCode = "UNAUTHORIZED"
	ErrCodeForbidden    ErrorCode = "FORBIDDEN"
	ErrCodeConflict     ErrorCode = "CONFLICT"
	ErrCodeValidation   ErrorCode = "VALIDATION_ERROR"
	ErrCodeRateLimit    ErrorCode = "RATE_LIMIT"
	ErrCodeTimeout      ErrorCode = "TIMEOUT"
	ErrCodeUnavailable  ErrorCode = "SERVICE_UNAVAILABLE"

	// Authentication errors
	ErrCodeInvalidCredentials ErrorCode = "INVALID_CREDENTIALS"
	ErrCodeTokenExpired       ErrorCode = "TOKEN_EXPIRED"
	ErrCodeTokenInvalid       ErrorCode = "TOKEN_INVALID"
	ErrCodeAccountLocked      ErrorCode = "ACCOUNT_LOCKED"
	ErrCodeAccountDisabled    ErrorCode = "ACCOUNT_DISABLED"

	// Authorization errors
	ErrCodeInsufficientPermissions ErrorCode = "INSUFFICIENT_PERMISSIONS"
	ErrCodeRoleRequired            ErrorCode = "ROLE_REQUIRED"
	ErrCodeScopeRequired           ErrorCode = "SCOPE_REQUIRED"

	// Business logic errors
	ErrCodeUserNotFound     ErrorCode = "USER_NOT_FOUND"
	ErrCodeUserExists       ErrorCode = "USER_EXISTS"
	ErrCodeTenantNotFound   ErrorCode = "TENANT_NOT_FOUND"
	ErrCodeTenantExists     ErrorCode = "TENANT_EXISTS"
	ErrCodeResourceNotFound ErrorCode = "RESOURCE_NOT_FOUND"
	ErrCodeResourceExists   ErrorCode = "RESOURCE_EXISTS"
	ErrCodeLimitExceeded    ErrorCode = "LIMIT_EXCEEDED"
	ErrCodeQuotaExceeded    ErrorCode = "QUOTA_EXCEEDED"

	// Database errors
	ErrCodeDatabaseConnection ErrorCode = "DATABASE_CONNECTION"
	ErrCodeDatabaseTimeout    ErrorCode = "DATABASE_TIMEOUT"
	ErrCodeDatabaseConstraint ErrorCode = "DATABASE_CONSTRAINT"
	ErrCodeDatabaseMigration  ErrorCode = "DATABASE_MIGRATION"

	// External service errors
	ErrCodeExternalService     ErrorCode = "EXTERNAL_SERVICE_ERROR"
	ErrCodePaymentRequired     ErrorCode = "PAYMENT_REQUIRED"
	ErrCodeSubscriptionExpired ErrorCode = "SUBSCRIPTION_EXPIRED"

	// File/Upload errors
	ErrCodeFileNotFound    ErrorCode = "FILE_NOT_FOUND"
	ErrCodeFileTooLarge    ErrorCode = "FILE_TOO_LARGE"
	ErrCodeFileTypeInvalid ErrorCode = "FILE_TYPE_INVALID"
	ErrCodeUploadFailed    ErrorCode = "UPLOAD_FAILED"
	ErrCodeStorageQuota    ErrorCode = "STORAGE_QUOTA_EXCEEDED"

	// Validation errors
	ErrCodeRequiredField ErrorCode = "REQUIRED_FIELD"
	ErrCodeInvalidFormat ErrorCode = "INVALID_FORMAT"
	ErrCodeInvalidLength ErrorCode = "INVALID_LENGTH"
	ErrCodeInvalidRange  ErrorCode = "INVALID_RANGE"
	ErrCodeInvalidEmail  ErrorCode = "INVALID_EMAIL"
	ErrCodeInvalidURL    ErrorCode = "INVALID_URL"
)

func GetCode

func GetCode(err error) ErrorCode

GetCode extracts error code from error

type ErrorHandler

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

ErrorHandler provides centralized error handling

func NewErrorHandler

func NewErrorHandler(logger Logger, config HandlerConfig) *ErrorHandler

NewErrorHandler creates a new error handler

func (*ErrorHandler) Handle

func (eh *ErrorHandler) Handle(err error, requestID, userID, tenantID string) *ErrorResponse

Handle handles an error and returns appropriate HTTP response

type ErrorInfo

type ErrorInfo struct {
	Code       string                 `json:"code"`
	Message    string                 `json:"message"`
	Details    map[string]interface{} `json:"details,omitempty"`
	Timestamp  time.Time              `json:"timestamp"`
	StackTrace []string               `json:"stack_trace,omitempty"`
}

ErrorInfo represents error information in response

type ErrorResponse

type ErrorResponse struct {
	Error     ErrorInfo `json:"error"`
	Status    int       `json:"status"`
	RequestID string    `json:"request_id,omitempty"`
}

ErrorResponse represents HTTP error response

func (*ErrorResponse) JSON

func (er *ErrorResponse) JSON() ([]byte, error)

JSON returns JSON representation of error response

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity represents error severity levels

const (
	SeverityLow      ErrorSeverity = "low"
	SeverityMedium   ErrorSeverity = "medium"
	SeverityHigh     ErrorSeverity = "high"
	SeverityCritical ErrorSeverity = "critical"
)

func GetSeverity

func GetSeverity(err error) ErrorSeverity

GetSeverity extracts error severity from error

type HandlerConfig

type HandlerConfig struct {
	IncludeStackTrace bool          `json:"include_stack_trace"`
	IncludeDetails    bool          `json:"include_details"`
	LogLevel          ErrorSeverity `json:"log_level"`
}

HandlerConfig represents error handler configuration

type Logger

type Logger interface {
	Error(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Debug(msg string, fields ...interface{})
}

Logger interface for error logging

type RecoveryMiddleware

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

RecoveryMiddleware provides panic recovery

func NewRecoveryMiddleware

func NewRecoveryMiddleware(errorHandler *ErrorHandler, logger Logger) *RecoveryMiddleware

NewRecoveryMiddleware creates new recovery middleware

func (*RecoveryMiddleware) Recover

func (rm *RecoveryMiddleware) Recover(requestID, userID, tenantID string) error

Recover recovers from panic and converts to error

type ValidationError

type ValidationError struct {
	Errors map[string]string `json:"errors"`
}

ValidationError represents multiple validation errors

func NewValidationError

func NewValidationError(errors map[string]string) *ValidationError

NewValidationError creates a validation error

func (*ValidationError) Add

func (ve *ValidationError) Add(field, message string)

Add adds a validation error

func (*ValidationError) Error

func (ve *ValidationError) Error() string

Error implements error interface

func (*ValidationError) Has

func (ve *ValidationError) Has() bool

Has checks if there are any validation errors

func (*ValidationError) ToAstraError

func (ve *ValidationError) ToAstraError() *Error

ToAstraError converts to Astra error

Jump to

Keyboard shortcuts

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