core

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package core provides the core error handling functionality for the application.

Package core provides the core error handling functionality for the errors package. It includes error codes, error context, and basic error types.

Package core provides the core error handling functionality for the errors package.

Package core provides the core error handling functionality for the errors package.

Index

Constants

This section is empty.

Variables

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

	// ErrAlreadyExists is returned when a resource already exists
	ErrAlreadyExists = fmt.Errorf("resource already exists")

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

	// ErrInternal is returned when an internal error occurs
	ErrInternal = fmt.Errorf("internal error")

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

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

	// ErrTimeout is returned when an operation times out
	ErrTimeout = fmt.Errorf("operation timed out")

	// ErrCancelled is returned when an operation is cancelled
	ErrCancelled = fmt.Errorf("operation cancelled")

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

Standard errors that can be used throughout the application

Map of error codes to HTTP status codes

Functions

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 BenchmarkContextualErrorCreation

func BenchmarkContextualErrorCreation(b *testing.B)

func BenchmarkErrorJSONMarshaling

func BenchmarkErrorJSONMarshaling(b *testing.B)

func BenchmarkErrorUnwrapping

func BenchmarkErrorUnwrapping(b *testing.B)

func BenchmarkErrorWrapping

func BenchmarkErrorWrapping(b *testing.B)

func BenchmarkGetCallerInfo

func BenchmarkGetCallerInfo(b *testing.B)

func GetCallerInfo

func GetCallerInfo(skip int) (string, int)

GetCallerInfo returns the file name and line number of the caller.

func GetHTTPStatus

func GetHTTPStatus(code ErrorCode) int

GetHTTPStatus returns the HTTP status code for an error code

func GetHTTPStatusFromError

func GetHTTPStatusFromError(err error) int

GetHTTPStatusFromError returns the HTTP status code from an error. If the error is a ContextualError, it returns the HTTP status from the context. If the error is a BaseError, it returns the HTTP status from the error code. Otherwise, it returns 500 (Internal Server Error). Parameters:

  • err: The error to get the HTTP status from

Returns:

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

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 ToJSON

func ToJSON(err error) string

ToJSON converts an error to a JSON string. If the error is a BaseError, 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 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 WithContext

func WithContext(err error, operation string, code ErrorCode, httpStatus int, details map[string]interface{}) error

WithContext wraps an error with contextual information. It adds operation name, error code, HTTP status, and source location to the error. If the error is already a ContextualError, it updates the context with the new information.

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 WrapWithOperation

func WrapWithOperation(err error, operation string) error

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

  • err: The error to wrap
  • operation: The name of the operation that failed

Returns:

  • error: A new error that wraps the original error

Types

type BaseError added in v1.4.0

type BaseError struct {
	// Code is a unique error code for categorizing errors
	Code ErrorCode `json:"code,omitempty"`

	// Message is a human-readable error message
	Message string `json:"message,omitempty"`

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

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

	// Cause is the underlying error that caused this error
	Cause error `json:"-"`

	// 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"`
}

BaseError is the foundation for all error types in the system. It provides common functionality for all errors, including error code, message, operation, details, cause, and stack trace.

func NewBaseError added in v1.4.0

func NewBaseError(code ErrorCode, message string, cause error) *BaseError

NewBaseError creates a new BaseError with caller information.

func (*BaseError) As added in v1.4.0

func (e *BaseError) As(target interface{}) bool

As finds the first error in err's chain that matches target.

func (*BaseError) Error added in v1.4.0

func (e *BaseError) Error() string

Error returns a string representation of the error.

func (*BaseError) GetCause added in v1.4.0

func (e *BaseError) GetCause() error

GetCause returns the underlying error.

func (*BaseError) GetCode added in v1.4.0

func (e *BaseError) GetCode() ErrorCode

GetCode returns the error code.

func (*BaseError) GetDetails added in v1.4.0

func (e *BaseError) GetDetails() map[string]interface{}

GetDetails returns additional details about the error.

func (*BaseError) GetHTTPStatus added in v1.4.0

func (e *BaseError) GetHTTPStatus() int

GetHTTPStatus returns the HTTP status code for the error.

func (*BaseError) GetLine added in v1.4.0

func (e *BaseError) GetLine() int

GetLine returns the line number where the error occurred.

func (*BaseError) GetMessage added in v1.4.0

func (e *BaseError) GetMessage() string

GetMessage returns the error message.

func (*BaseError) GetOperation added in v1.4.0

func (e *BaseError) GetOperation() string

GetOperation returns the operation that failed.

func (*BaseError) GetSource added in v1.4.0

func (e *BaseError) GetSource() string

GetSource returns the source location of the error.

func (*BaseError) Is added in v1.4.0

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

Is reports whether the error is of the given target type.

func (*BaseError) MarshalJSON added in v1.4.0

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

MarshalJSON implements the json.Marshaler interface.

func (*BaseError) Unwrap added in v1.4.0

func (e *BaseError) Unwrap() error

Unwrap returns the underlying error.

func (*BaseError) WithDetails added in v1.4.0

func (e *BaseError) WithDetails(details map[string]interface{}) *BaseError

WithDetails adds details to the error.

func (*BaseError) WithOperation added in v1.4.0

func (e *BaseError) WithOperation(operation string) *BaseError

WithOperation adds an operation to the error.

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 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. If the error is a BaseError, it returns the code from the BaseError. Otherwise, it returns InternalErrorCode. Parameters:

  • err: The error to get the code from

Returns:

  • ErrorCode: The error code, or InternalErrorCode 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.

Jump to

Keyboard shortcuts

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