errors

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2025 License: MIT Imports: 7 Imported by: 0

README

ServiceLib Error Handling

This package provides a comprehensive error handling system for the application. It includes error codes, HTTP status mapping, contextual information, and utilities for creating, wrapping, and serializing errors.

Package Structure

The error handling package is organized into several sub-packages:

  • core: Core error handling functionality (error codes, error context, utility functions)

  • types: Specific error types (validation errors, application errors, domain errors, repository errors)

  • interfaces: Error interfaces for type checking and HTTP status mapping

  • recovery: Error recovery mechanisms (circuit breakers, retries)

  • utils: Utility functions for error handling

  • wrappers: Error wrapping utilities

  • Features:

    • Error wrapping with context
    • Error codes
    • Localized error messages
    • Stack traces
    • Error categorization
    • HTTP status mapping
    • Error recovery mechanisms

Installation

go get github.com/abitofhelp/servicelib/errors

Usage

Basic Error Creation
package main

import (
    "fmt"
    "github.com/abitofhelp/servicelib/errors"
)

func main() {
    // Create a simple error
    err := errors.New("something went wrong")
    fmt.Println(err) // Output: something went wrong

    // Create an error with a code
    err = errors.NewWithCode("invalid_input", "Invalid input provided")
    fmt.Println(err) // Output: invalid_input: Invalid input provided

    // Create a domain error
    err = errors.NewDomainError("user_not_found", "User not found")
    fmt.Println(err) // Output: domain error: user_not_found: User not found

    // Create an infrastructure error
    err = errors.NewInfrastructureError("database_connection", "Failed to connect to database")
    fmt.Println(err) // Output: infrastructure error: database_connection: Failed to connect to database

    // Create an application error
    err = errors.NewApplicationError("invalid_state", "Application is in an invalid state")
    fmt.Println(err) // Output: application error: invalid_state: Application is in an invalid state

    // Create a validation error
    err = errors.NewValidationError("required_field", "Field 'name' is required")
    fmt.Println(err) // Output: validation error: required_field: Field 'name' is required
}
Error Wrapping
package main

import (
    "database/sql"
    "fmt"
    "github.com/abitofhelp/servicelib/errors"
)

func main() {
    // Wrap a standard error
    originalErr := sql.ErrNoRows
    wrappedErr := errors.Wrap(originalErr, "failed to find user")
    fmt.Println(wrappedErr) // Output: failed to find user: sql: no rows in result set

    // Wrap with a code
    wrappedWithCode := errors.WrapWithCode(originalErr, "user_not_found", "failed to find user")
    fmt.Println(wrappedWithCode) // Output: user_not_found: failed to find user: sql: no rows in result set

    // Wrap multiple times
    deeplyWrapped := errors.Wrap(wrappedErr, "error in GetUserByID")
    fmt.Println(deeplyWrapped) // Output: error in GetUserByID: failed to find user: sql: no rows in result set

    // Unwrap to get the original error
    unwrapped := errors.Unwrap(deeplyWrapped)
    fmt.Println(unwrapped) // Output: failed to find user: sql: no rows in result set

    // Check if an error is of a specific type
    if errors.Is(deeplyWrapped, sql.ErrNoRows) {
        fmt.Println("The original error was sql.ErrNoRows")
    }
}
Error Context
package main

import (
    "fmt"
    "github.com/abitofhelp/servicelib/errors"
)

func main() {
    // Create an error with context
    err := errors.NewWithContext("failed to process request", map[string]interface{}{
        "user_id": "123",
        "action":  "create_order",
        "status":  "failed",
    })

    // Get context from the error
    if ctx, ok := errors.GetContext(err); ok {
        fmt.Printf("Error context: %v\n", ctx)
    }

    // Get a specific context value
    if userID, ok := errors.GetContextValue(err, "user_id"); ok {
        fmt.Printf("User ID: %v\n", userID)
    }

    // Add more context to an existing error
    enrichedErr := errors.AddContext(err, "request_id", "req-456")

    // Get the enriched context
    if ctx, ok := errors.GetContext(enrichedErr); ok {
        fmt.Printf("Enriched context: %v\n", ctx)
    }
}
Error Categorization
package main

import (
    "fmt"
    "github.com/abitofhelp/servicelib/errors"
)

func main() {
    // Create errors of different types
    notFoundErr := errors.NewDomainError("user_not_found", "User not found")
    validationErr := errors.NewValidationError("invalid_email", "Email is invalid")
    authErr := errors.NewApplicationError("unauthorized", "User is not authorized")
    dbErr := errors.NewInfrastructureError("db_connection", "Failed to connect to database")

    // Check error categories
    fmt.Printf("Is not found: %v\n", errors.IsNotFound(notFoundErr))
    fmt.Printf("Is validation: %v\n", errors.IsValidation(validationErr))
    fmt.Printf("Is unauthorized: %v\n", errors.IsUnauthorized(authErr))
    fmt.Printf("Is infrastructure: %v\n", errors.IsInfrastructure(dbErr))

    // Use in error handling
    handleError(notFoundErr)
    handleError(validationErr)
    handleError(authErr)
    handleError(dbErr)
}

func handleError(err error) {
    switch {
    case errors.IsNotFound(err):
        fmt.Println("Handle not found error:", err)
    case errors.IsValidation(err):
        fmt.Println("Handle validation error:", err)
    case errors.IsUnauthorized(err):
        fmt.Println("Handle unauthorized error:", err)
    case errors.IsInfrastructure(err):
        fmt.Println("Handle infrastructure error:", err)
    default:
        fmt.Println("Handle generic error:", err)
    }
}
Stack Traces
package main

import (
    "fmt"
    "github.com/abitofhelp/servicelib/errors"
)

func main() {
    // Create an error with a stack trace
    err := errors.NewWithStack("something went wrong")

    // Print the error with stack trace
    fmt.Println(errors.StackTrace(err))

    // Create a function that returns an error
    err = someFunction()

    // Print the stack trace
    fmt.Println(errors.StackTrace(err))
}

func someFunction() error {
    return anotherFunction()
}

func anotherFunction() error {
    return errors.NewWithStack("error in anotherFunction")
}
Error Codes
package main

import (
    "fmt"
    "github.com/abitofhelp/servicelib/errors"
)

func main() {
    // Create an error with a code
    err := errors.NewWithCode("invalid_input", "Invalid input provided")

    // Get the error code
    if code, ok := errors.GetCode(err); ok {
        fmt.Printf("Error code: %s\n", code)
    }

    // Check if an error has a specific code
    if errors.HasCode(err, "invalid_input") {
        fmt.Println("This is an invalid input error")
    }

    // Create a wrapped error with a code
    originalErr := fmt.Errorf("value out of range")
    wrappedErr := errors.WrapWithCode(originalErr, "validation_error", "Input validation failed")

    // Get the code from the wrapped error
    if code, ok := errors.GetCode(wrappedErr); ok {
        fmt.Printf("Wrapped error code: %s\n", code)
    }
}
Localized Error Messages
package main

import (
    "fmt"
    "github.com/abitofhelp/servicelib/errors"
)

func main() {
    // Create an error with localized messages
    err := errors.NewLocalized("invalid_input", map[string]string{
        "en": "Invalid input provided",
        "es": "Entrada no válida proporcionada",
        "fr": "Entrée invalide fournie",
    })

    // Get the default message (usually English)
    fmt.Println(err) // Output: invalid_input: Invalid input provided

    // Get a localized message
    if msg, ok := errors.GetLocalizedMessage(err, "es"); ok {
        fmt.Printf("Spanish error message: %s\n", msg)
    }

    // Get a localized message with fallback
    msg := errors.GetLocalizedMessageWithFallback(err, "de", "en")
    fmt.Printf("German message (fallback to English): %s\n", msg)
}

Best Practices

  1. Use Structured Errors: Create structured errors with codes and context information to make debugging easier.

    return errors.NewWithContext("failed to process order", map[string]interface{}{
        "order_id": orderID,
        "user_id": userID,
        "status": "failed",
    })
    
  2. Error Categorization: Categorize errors to handle them appropriately at the API boundary.

    switch {
    case errors.IsNotFound(err):
        return http.StatusNotFound, errorResponse(err)
    case errors.IsValidation(err):
        return http.StatusBadRequest, errorResponse(err)
    case errors.IsUnauthorized(err):
        return http.StatusUnauthorized, errorResponse(err)
    default:
        return http.StatusInternalServerError, errorResponse(err)
    }
    
  3. Wrap Errors: Wrap errors to add context as they propagate up the call stack.

    if err := repository.GetUser(id); err != nil {
        return errors.Wrap(err, "failed to get user")
    }
    
  4. Error Codes: Use consistent error codes across your application.

    const (
        ErrNotFound      = "not_found"
        ErrInvalidInput  = "invalid_input"
        ErrUnauthorized  = "unauthorized"
        ErrInternal      = "internal_error"
    )
    
  5. Stack Traces: Include stack traces for unexpected errors to aid debugging.

    if err != nil && !isExpectedError(err) {
        return errors.NewWithStack(fmt.Sprintf("unexpected error: %v", err))
    }
    

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package errors provides a comprehensive error handling system for the application. It includes error codes, HTTP status mapping, contextual information, and utilities for creating, wrapping, and serializing errors.

Package errors provides generic error interfaces and implementations that can be used across different applications.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a requested resource is not found
	ErrNotFound = errors.New("resource not found")

	// ErrAlreadyExists is returned when a resource already exists
	ErrAlreadyExists = errors.New("resource already exists")

	// ErrInvalidInput is returned when the input to a function is invalid
	ErrInvalidInput = errors.New("invalid input")

	// ErrInternal is returned when an internal error occurs
	ErrInternal = errors.New("internal error")

	// ErrUnauthorized is returned when a user is not authorized to perform an action
	ErrUnauthorized = errors.New("unauthorized")

	// ErrForbidden is returned when a user is forbidden from performing an action
	ErrForbidden = errors.New("forbidden")

	// ErrTimeout is returned when an operation times out
	ErrTimeout = errors.New("operation timed out")

	// ErrCancelled is returned when an operation is cancelled
	ErrCancelled = errors.New("operation cancelled")

	// ErrConflict is returned when there is a conflict with the current state
	ErrConflict = errors.New("conflict with current state")
)

Standard errors that can be used throughout the application

Functions

func AlreadyExists

func AlreadyExists(format string, args ...interface{}) error

AlreadyExists creates a new error for when a resource already exists. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with AlreadyExistsCode and HTTP 409 status

func As

func As(err error, target interface{}) bool

As finds the first error in err's chain that matches target. This is a wrapper around errors.As that adds support for ContextualError. Parameters:

  • err: The error to check
  • target: A pointer to the error type to match against

Returns:

  • bool: True if a match was found

func BusinessRuleViolation

func BusinessRuleViolation(format string, args ...interface{}) error

BusinessRuleViolation creates a new error for when a business rule is violated. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with BusinessRuleViolationCode and HTTP 422 status

func Canceled

func Canceled(format string, args ...interface{}) error

Canceled creates a new error for when an operation is canceled. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with CanceledCode and HTTP 408 status

func Concurrency

func Concurrency(format string, args ...interface{}) error

Concurrency creates a new error for concurrency-related errors. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with ConcurrencyErrorCode and HTTP 409 status

func Configuration

func Configuration(format string, args ...interface{}) error

Configuration creates a new error for configuration errors. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with ConfigurationErrorCode and HTTP 500 status

func DataCorruption

func DataCorruption(format string, args ...interface{}) error

DataCorruption creates a new error for when data is corrupted. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with DataCorruptionCode and HTTP 500 status

func DatabaseOperation

func DatabaseOperation(err error, format string, args ...interface{}) error

DatabaseOperation creates a new error for database operation failures. Parameters:

  • err: The original error
  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with DatabaseErrorCode and HTTP 500 status

func ExternalService

func ExternalService(err error, service string, format string, args ...interface{}) error

ExternalService creates a new error for external service call failures. Parameters:

  • err: The original error
  • service: The name of the external service
  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with ExternalServiceErrorCode and HTTP 502 status

func Forbidden

func Forbidden(format string, args ...interface{}) error

Forbidden creates a new error for authorization failures. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with ForbiddenCode and HTTP 403 status

func GetHTTPStatus

func GetHTTPStatus(err error) int

GetHTTPStatus returns the HTTP status code from an error. If the error is a ContextualError, it returns the HTTP status from the context. Otherwise, it returns 0. Parameters:

  • err: The error to get the HTTP status from

Returns:

  • int: The HTTP status code, or 0 if not available

func GetHTTPStatusFromError

func GetHTTPStatusFromError(err error) int

GetHTTPStatusFromError returns the HTTP status code for an error

func Internal

func Internal(err error, format string, args ...interface{}) error

Internal creates a new error for internal server errors. Parameters:

  • err: The original error
  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with InternalErrorCode and HTTP 500 status

func InvalidInput

func InvalidInput(format string, args ...interface{}) error

InvalidInput creates a new error for when input validation fails. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with InvalidInputCode and HTTP 400 status

func Is

func Is(err error, target error) bool

Is checks if an error matches a target error. This is a wrapper around errors.Is that adds support for ContextualError. Parameters:

  • err: The error to check
  • target: The target error to match against

Returns:

  • bool: True if the error matches the target

func IsApplicationError

func IsApplicationError(err error) bool

IsApplicationError checks if an error is an application error

func IsCancelled

func IsCancelled(err error) bool

IsCancelled returns true if the error is a cancelled error

func IsConflict

func IsConflict(err error) bool

IsConflict returns true if the error is a conflict error

func IsForbidden

func IsForbidden(err error) bool

IsForbidden returns true if the error is a forbidden error

func IsInternal

func IsInternal(err error) bool

IsInternal returns true if the error is an internal error

func IsInvalidInput

func IsInvalidInput(err error) bool

IsInvalidInput returns true if the error is an invalid input error

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error is a not found error

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError checks if an error is a not found error

func IsRepositoryError

func IsRepositoryError(err error) bool

IsRepositoryError checks if an error is a repository error

func IsTimeout

func IsTimeout(err error) bool

IsTimeout returns true if the error is a timeout error

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized returns true if the error is an unauthorized error

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if an error is a validation error

func Network

func Network(err error, format string, args ...interface{}) error

Network creates a new error for network-related errors. Parameters:

  • err: The original error
  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with NetworkErrorCode and HTTP 503 status

func New

func New(op, code, message string, original error) error

New creates a new Error

func NotFound

func NotFound(format string, args ...interface{}) error

NotFound creates a new error for when a resource is not found. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with NotFoundCode and HTTP 404 status

func ResourceExhausted

func ResourceExhausted(format string, args ...interface{}) error

ResourceExhausted creates a new error for when a resource limit is reached. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with ResourceExhaustedCode and HTTP 429 status

func Timeout

func Timeout(format string, args ...interface{}) error

Timeout creates a new error for when an operation times out. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with TimeoutCode and HTTP 504 status

func ToJSON

func ToJSON(err error) string

ToJSON converts an error to a JSON string. If the error is a ContextualError, it uses the MarshalJSON method. Otherwise, it creates a simple JSON object with the error message. Parameters:

  • err: The error to convert to JSON

Returns:

  • string: The JSON representation of the error

func Unauthorized

func Unauthorized(format string, args ...interface{}) error

Unauthorized creates a new error for authentication failures. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with UnauthorizedCode and HTTP 401 status

func Unwrap

func Unwrap(err error) error

Unwrap returns the underlying error. This is a wrapper around errors.Unwrap that adds support for ContextualError. Parameters:

  • err: The error to unwrap

Returns:

  • error: The underlying error, or nil if there is none

func Validation

func Validation(format string, args ...interface{}) error

Validation creates a new error for domain validation errors. Parameters:

  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error with ValidationErrorCode and HTTP 400 status

func WithDetails

func WithDetails(err error, details map[string]interface{}) error

WithDetails adds details to an error. It preserves the error chain and adds additional context information. Parameters:

  • err: The error to enhance
  • details: A map of additional details to add to the error

Returns:

  • error: A new error with the added details

func Wrap

func Wrap(err error, op, message string) error

Wrap wraps an error with additional context

func WrapWithOperation

func WrapWithOperation(err error, operation string, format string, args ...interface{}) error

WrapWithOperation wraps an error with an operation name and message. It preserves the error chain and adds source location information. Parameters:

  • err: The error to wrap
  • operation: The name of the operation that failed
  • format: The error message format string
  • args: Arguments for the format string

Returns:

  • error: A new error that wraps the original error

Types

type AppError

type AppError[T ~string] struct {
	Err     error
	Message string
	Code    string
	Type    T
}

AppError is a generic error type that can be used for different error categories

func NewAppError

func NewAppError[T ~string](err error, message, code string, errorType T) *AppError[T]

NewAppError creates a new AppError

func (*AppError[T]) Error

func (e *AppError[T]) Error() string

func (*AppError[T]) ErrorType

func (e *AppError[T]) ErrorType() T

func (*AppError[T]) Unwrap

func (e *AppError[T]) Unwrap() error

type ApplicationError

type ApplicationError struct {
	Err     error
	Message string
	Code    string
}

ApplicationError represents an error that occurred in the application layer

func NewApplicationError

func NewApplicationError(err error, message, code string) *ApplicationError

NewApplicationError creates a new ApplicationError

func (*ApplicationError) Error

func (e *ApplicationError) Error() string

func (*ApplicationError) Unwrap

func (e *ApplicationError) Unwrap() error

type ApplicationErrorInterface

type ApplicationErrorInterface interface {
	ErrorWithCode
	ErrorWithHTTPStatus
	// IsApplicationError identifies this as an application error
	IsApplicationError() bool
}

ApplicationErrorInterface is an interface for application errors

type ContextualError

type ContextualError struct {
	// Original is the original error that was wrapped
	Original error

	// Context contains additional information about the error
	Context ErrorContext
}

ContextualError is an error with additional context. It wraps another error and adds contextual information like operation name, error code, HTTP status, and source location.

func (*ContextualError) Code

func (e *ContextualError) Code() ErrorCode

Code returns the error code.

func (*ContextualError) Error

func (e *ContextualError) Error() string

Error returns the error message with contextual information.

func (*ContextualError) HTTPStatus

func (e *ContextualError) HTTPStatus() int

HTTPStatus returns the HTTP status code.

func (*ContextualError) MarshalJSON

func (e *ContextualError) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*ContextualError) Unwrap

func (e *ContextualError) Unwrap() error

Unwrap returns the original error.

type DomainError

type DomainError = AppError[DomainErrorType]

DomainError represents an error that occurred in the domain layer

func NewDomainError

func NewDomainError(err error, message, code string) *DomainError

NewDomainError creates a new DomainError

type DomainErrorType

type DomainErrorType string

DomainErrorType represents the type of domain error

const (
	DomainErrorGeneral DomainErrorType = "DOMAIN_ERROR"
)

Domain error type constants

type Error

type Error struct {
	// Original is the original error
	Original error

	// Code is a machine-readable error code
	Code string

	// Message is a human-readable error message
	Message string

	// Op is the operation that caused the error
	Op string

	// Param is the parameter that caused the error
	Param string
}

Error represents a domain error with operation context

func (*Error) Error

func (e *Error) Error() string

Error returns a string representation of the error

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether the error is of the given target type

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the original error

type ErrorCode

type ErrorCode string

ErrorCode represents a unique error code for categorizing errors. These codes are used for error identification, logging, and mapping to HTTP status codes.

const (
	// NotFoundCode is used when a resource is not found.
	// Maps to HTTP 404 Not Found.
	NotFoundCode ErrorCode = "NOT_FOUND"

	// InvalidInputCode is used when input validation fails.
	// Maps to HTTP 400 Bad Request.
	InvalidInputCode ErrorCode = "INVALID_INPUT"

	// DatabaseErrorCode is used for database operation failures.
	// Maps to HTTP 500 Internal Server Error.
	DatabaseErrorCode ErrorCode = "DATABASE_ERROR"

	// InternalErrorCode is used for internal server errors.
	// Maps to HTTP 500 Internal Server Error.
	InternalErrorCode ErrorCode = "INTERNAL_ERROR"

	// TimeoutCode is used when an operation times out.
	// Maps to HTTP 504 Gateway Timeout.
	TimeoutCode ErrorCode = "TIMEOUT"

	// CanceledCode is used when an operation is canceled.
	// Maps to HTTP 408 Request Timeout.
	CanceledCode ErrorCode = "CANCELED"

	// AlreadyExistsCode is used when a resource already exists.
	// Maps to HTTP 409 Conflict.
	AlreadyExistsCode ErrorCode = "ALREADY_EXISTS"

	// UnauthorizedCode is used for authentication failures.
	// Maps to HTTP 401 Unauthorized.
	UnauthorizedCode ErrorCode = "UNAUTHORIZED"

	// ForbiddenCode is used for authorization failures.
	// Maps to HTTP 403 Forbidden.
	ForbiddenCode ErrorCode = "FORBIDDEN"

	// ValidationErrorCode is used for domain validation errors.
	// Maps to HTTP 400 Bad Request.
	ValidationErrorCode ErrorCode = "VALIDATION_ERROR"

	// BusinessRuleViolationCode is used when a business rule is violated.
	// Maps to HTTP 422 Unprocessable Entity.
	BusinessRuleViolationCode ErrorCode = "BUSINESS_RULE_VIOLATION"

	// ExternalServiceErrorCode is used when an external service call fails.
	// Maps to HTTP 502 Bad Gateway.
	ExternalServiceErrorCode ErrorCode = "EXTERNAL_SERVICE_ERROR"

	// NetworkErrorCode is used for network-related errors.
	// Maps to HTTP 503 Service Unavailable.
	NetworkErrorCode ErrorCode = "NETWORK_ERROR"

	// ConfigurationErrorCode is used for configuration errors.
	// Maps to HTTP 500 Internal Server Error.
	ConfigurationErrorCode ErrorCode = "CONFIGURATION_ERROR"

	// ResourceExhaustedCode is used when a resource limit is reached.
	// Maps to HTTP 429 Too Many Requests.
	ResourceExhaustedCode ErrorCode = "RESOURCE_EXHAUSTED"

	// DataCorruptionCode is used when data is corrupted.
	// Maps to HTTP 500 Internal Server Error.
	DataCorruptionCode ErrorCode = "DATA_CORRUPTION"

	// ConcurrencyErrorCode is used for concurrency-related errors.
	// Maps to HTTP 409 Conflict.
	ConcurrencyErrorCode ErrorCode = "CONCURRENCY_ERROR"
)

Standard error codes define all possible error categories in the application.

func GetCode

func GetCode(err error) ErrorCode

GetCode returns the error code from an error. If the error is a ContextualError, it returns the code from the context. Otherwise, it returns an empty string. Parameters:

  • err: The error to get the code from

Returns:

  • ErrorCode: The error code, or an empty string if not available

type ErrorContext

type ErrorContext struct {
	// Operation is the name of the operation that failed
	Operation string `json:"operation,omitempty"`

	// Source is the file and line where the error occurred
	Source string `json:"source,omitempty"`

	// Line is the line number where the error occurred
	Line int `json:"line,omitempty"`

	// Code is the error code
	Code ErrorCode `json:"code,omitempty"`

	// HTTPStatus is the HTTP status code to return for this error
	HTTPStatus int `json:"http_status,omitempty"`

	// Details contains additional information about the error
	Details map[string]interface{} `json:"details,omitempty"`
}

ErrorContext holds additional context for an error. It includes information about the operation that failed, the source location, and any additional details that might be useful for debugging or error reporting.

type ErrorWithCode

type ErrorWithCode interface {
	error
	// Code returns the error code
	Code() string
}

ErrorWithCode is an interface for errors that have an error code

type ErrorWithHTTPStatus

type ErrorWithHTTPStatus interface {
	error
	// HTTPStatus returns the HTTP status code
	HTTPStatus() int
}

ErrorWithHTTPStatus is an interface for errors that have an HTTP status code

type GenericError

type GenericError[T any] struct {
	Err      error
	Message  string
	Code     string
	Category T
}

GenericError is a generic error type that can be used for different error categories

func NewGenericError

func NewGenericError[T any](err error, message, code string, category T) *GenericError[T]

NewGenericError creates a new GenericError

func (*GenericError[T]) Error

func (e *GenericError[T]) Error() string

func (*GenericError[T]) Unwrap

func (e *GenericError[T]) Unwrap() error

type NotFoundError

type NotFoundError struct {
	ResourceType string
	ID           string
}

NotFoundError represents a resource not found error

func NewNotFoundError

func NewNotFoundError(resourceType, id string) *NotFoundError

NewNotFoundError creates a new NotFoundError

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) Is

func (e *NotFoundError) Is(target error) bool

Is implements the errors.Is interface for NotFoundError

type NotFoundErrorInterface

type NotFoundErrorInterface interface {
	ErrorWithCode
	ErrorWithHTTPStatus
	// IsNotFoundError identifies this as a not found error
	IsNotFoundError() bool
}

NotFoundErrorInterface is an interface for not found errors

type RepositoryError

type RepositoryError struct {
	Err     error
	Message string
	Code    string
}

RepositoryError represents an error that occurred in the repository layer

func NewRepositoryError

func NewRepositoryError(err error, message, code string) *RepositoryError

NewRepositoryError creates a new RepositoryError

func (*RepositoryError) Error

func (e *RepositoryError) Error() string

func (*RepositoryError) Unwrap

func (e *RepositoryError) Unwrap() error

type RepositoryErrorInterface

type RepositoryErrorInterface interface {
	ErrorWithCode
	ErrorWithHTTPStatus
	// IsRepositoryError identifies this as a repository error
	IsRepositoryError() bool
}

RepositoryErrorInterface is an interface for repository errors

type ValidationError

type ValidationError struct {
	Msg   string
	Field string
}

ValidationError represents a validation error

func NewFieldValidationError

func NewFieldValidationError(msg, field string) *ValidationError

NewFieldValidationError creates a new ValidationError with a field name

func NewValidationError

func NewValidationError(msg string) *ValidationError

NewValidationError creates a new ValidationError

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationErrorInterface

type ValidationErrorInterface interface {
	ErrorWithCode
	ErrorWithHTTPStatus
	// IsValidationError identifies this as a validation error
	IsValidationError() bool
}

ValidationErrorInterface is an interface for validation errors

type ValidationErrors

type ValidationErrors struct {
	Errors []*ValidationError
}

ValidationErrors represents multiple validation errors

func NewValidationErrors

func NewValidationErrors(errors ...*ValidationError) *ValidationErrors

NewValidationErrors creates a new ValidationErrors

func (*ValidationErrors) AddError

func (e *ValidationErrors) AddError(err *ValidationError)

AddError adds a validation error to the collection

func (*ValidationErrors) Error

func (e *ValidationErrors) Error() string

func (*ValidationErrors) HasErrors

func (e *ValidationErrors) HasErrors() bool

HasErrors returns true if there are any validation errors

Directories

Path Synopsis
Package core provides the core error handling functionality for the errors package.
Package core provides the core error handling functionality for the errors package.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package types provides specific error types for the errors package.
Package types provides specific error types for the errors package.

Jump to

Keyboard shortcuts

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