errors

package
v0.90.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: AGPL-3.0 Imports: 6 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// CodeOK indicates success (not an error).
	CodeOK = "OK"

	// CodeCancelled indicates the operation was cancelled.
	CodeCancelled = "CANCELLED"

	// CodeUnknown indicates an unknown error occurred.
	CodeUnknown = "UNKNOWN"

	// CodeInvalidArgument indicates client specified an invalid argument.
	CodeInvalidArgument = "INVALID_ARGUMENT"

	// CodeDeadlineExceeded indicates operation deadline was exceeded.
	CodeDeadlineExceeded = "DEADLINE_EXCEEDED"

	// CodeNotFound indicates a resource was not found.
	CodeNotFound = "NOT_FOUND"

	// CodeAlreadyExists indicates attempting to create a resource that already exists.
	CodeAlreadyExists = "ALREADY_EXISTS"

	// CodePermissionDenied indicates the caller doesn't have permission.
	CodePermissionDenied = "PERMISSION_DENIED"

	// CodeResourceExhausted indicates a resource has been exhausted.
	CodeResourceExhausted = "RESOURCE_EXHAUSTED"

	// CodeFailedPrecondition indicates operation was rejected because the system
	// is not in a required state.
	CodeFailedPrecondition = "FAILED_PRECONDITION"

	// CodeAborted indicates the operation was aborted.
	CodeAborted = "ABORTED"

	// CodeOutOfRange indicates operation attempted past valid range.
	CodeOutOfRange = "OUT_OF_RANGE"

	// CodeUnimplemented indicates operation is not implemented or not supported.
	CodeUnimplemented = "UNIMPLEMENTED"

	// CodeInternal indicates internal errors.
	CodeInternal = "INTERNAL"

	// CodeUnavailable indicates the service is currently unavailable.
	CodeUnavailable = "UNAVAILABLE"

	// CodeDataLoss indicates unrecoverable data loss or corruption.
	CodeDataLoss = "DATA_LOSS"

	// CodeUnauthenticated indicates the request does not have valid authentication.
	CodeUnauthenticated = "UNAUTHENTICATED"

	// CodeValidation indicates input validation failed.
	CodeValidation = "VALIDATION_ERROR"

	// CodeUnauthorized indicates authentication is required or failed.
	CodeUnauthorized = "UNAUTHORIZED"

	// CodeForbidden indicates the authenticated user lacks permission.
	CodeForbidden = "FORBIDDEN"

	// CodeConflict indicates a resource conflict (e.g., duplicate key).
	CodeConflict = "CONFLICT"

	// CodeTimeout indicates an operation timed out.
	CodeTimeout = "TIMEOUT"

	// CodeRateLimit indicates rate limit was exceeded.
	CodeRateLimit = "RATE_LIMIT_EXCEEDED"

	// CodeServiceUnavailable indicates a downstream service is unavailable.
	CodeServiceUnavailable = "SERVICE_UNAVAILABLE"

	// CodeDatabaseError indicates a database operation failed.
	CodeDatabaseError = "DATABASE_ERROR"

	// CodeCacheError indicates a cache operation failed.
	CodeCacheError = "CACHE_ERROR"

	// CodeStorageError indicates a storage operation failed.
	CodeStorageError = "STORAGE_ERROR"

	// CodeNetworkError indicates a network operation failed.
	CodeNetworkError = "NETWORK_ERROR"

	// CodeExecutionError indicates a WASM or function execution failed.
	CodeExecutionError = "EXECUTION_ERROR"

	// CodeCompilationError indicates WASM compilation failed.
	CodeCompilationError = "COMPILATION_ERROR"

	// CodeConfigError indicates a configuration error.
	CodeConfigError = "CONFIG_ERROR"

	// CodeAuthError indicates an authentication/authorization error.
	CodeAuthError = "AUTH_ERROR"

	// CodeCryptoError indicates a cryptographic operation failed.
	CodeCryptoError = "CRYPTO_ERROR"

	// CodeSerializationError indicates serialization/deserialization failed.
	CodeSerializationError = "SERIALIZATION_ERROR"
)

Error codes for categorizing errors. These codes map to HTTP status codes and gRPC codes where applicable.

Variables

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

	// ErrUnauthorized is returned when authentication fails or is missing.
	ErrUnauthorized = errors.New("unauthorized")

	// ErrForbidden is returned when the user lacks permission for an action.
	ErrForbidden = errors.New("forbidden")

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

	// ErrInvalidInput is returned when request input is invalid.
	ErrInvalidInput = errors.New("invalid input")

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

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

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

	// ErrTooManyRequests is returned when rate limit is exceeded.
	ErrTooManyRequests = errors.New("too many requests")
)

Common sentinel errors for quick checks

Functions

func Cause

func Cause(err error) error

Cause returns the underlying cause of an error. It unwraps the error chain until it finds the root cause.

Example

Example demonstrates getting the root cause of an error chain.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	root := fmt.Errorf("database connection failed")
	level1 := errors.Wrap(root, "failed to fetch user")
	level2 := errors.Wrap(level1, "API request failed")

	cause := errors.Cause(level2)
	fmt.Println(cause.Error())
}
Output:

database connection failed

func GetErrorCode

func GetErrorCode(err error) string

GetErrorCode extracts the error code from an error.

func GetErrorMessage

func GetErrorMessage(err error) string

GetErrorMessage extracts a human-readable message from an error.

func HTTPStatusToCode

func HTTPStatusToCode(status int) string

HTTPStatusToCode converts an HTTP status code to an error code.

func IsClientError

func IsClientError(code string) bool

IsClientError returns true if the error is a client error (4xx).

func IsConflict

func IsConflict(err error) bool

IsConflict checks if an error indicates a resource conflict.

func IsForbidden

func IsForbidden(err error) bool

IsForbidden checks if an error indicates lack of authorization.

func IsInternal

func IsInternal(err error) bool

IsInternal checks if an error is an internal error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if an error indicates a resource was not found.

Example

Example demonstrates checking error types.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	err := errors.NewNotFoundError("user", "123")

	if errors.IsNotFound(err) {
		fmt.Println("User not found")
	}
}
Output:

User not found

func IsRateLimit

func IsRateLimit(err error) bool

IsRateLimit checks if an error indicates rate limiting.

func IsRetryable

func IsRetryable(code string) bool

IsRetryable returns true if an error with the given code should be retried.

func IsServerError

func IsServerError(code string) bool

IsServerError returns true if the error is a server error (5xx).

func IsServiceUnavailable

func IsServiceUnavailable(err error) bool

IsServiceUnavailable checks if an error indicates a service is unavailable.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout checks if an error indicates a timeout.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized checks if an error indicates lack of authentication.

func IsValidation

func IsValidation(err error) bool

IsValidation checks if an error is a validation error.

func New

func New(message string) error

New creates a new error with a message.

func Newf

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

Newf creates a new error with a formatted message.

func ShouldRetry

func ShouldRetry(err error) bool

ShouldRetry checks if an operation should be retried based on the error.

Example

Example demonstrates checking if an error should be retried.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	timeoutErr := errors.NewTimeoutError("database query", "5s")
	notFoundErr := errors.NewNotFoundError("user", "123")

	fmt.Println("Timeout should retry:", errors.ShouldRetry(timeoutErr))
	fmt.Println("Not found should retry:", errors.ShouldRetry(notFoundErr))
}
Output:

Timeout should retry: true
Not found should retry: false

func StatusCode

func StatusCode(err error) int

StatusCode returns the HTTP status code for an error. It maps error codes to appropriate HTTP status codes.

Example

Example demonstrates HTTP status code mapping.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	tests := []error{
		errors.NewValidationError("field", "invalid", nil),
		errors.NewNotFoundError("user", "123"),
		errors.NewUnauthorizedError("invalid token"),
		errors.NewForbiddenError("resource", "delete"),
		errors.NewTimeoutError("operation", "30s"),
	}

	for _, err := range tests {
		fmt.Printf("%s -> %d\n", errors.GetErrorCode(err), errors.StatusCode(err))
	}
}
Output:

VALIDATION_ERROR -> 400
NOT_FOUND -> 404
UNAUTHORIZED -> 401
FORBIDDEN -> 403
TIMEOUT -> 408

func Wrap

func Wrap(err error, message string) error

Wrap wraps an error with additional context. If the error is already one of our custom types, it preserves the type and adds the cause chain. Otherwise, it creates an InternalError.

Example

Example demonstrates wrapping errors with context.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	originalErr := errors.NewNotFoundError("user", "123")
	wrappedErr := errors.Wrap(originalErr, "failed to fetch user profile")

	fmt.Println(wrappedErr.Error())
	fmt.Println("Is NotFound:", errors.IsNotFound(wrappedErr))
}
Output:

failed to fetch user profile: user with ID '123' not found
Is NotFound: true

func Wrapf

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

Wrapf wraps an error with a formatted message.

func WriteHTTPError

func WriteHTTPError(w http.ResponseWriter, err error, traceID string)

WriteHTTPError writes an error response to an http.ResponseWriter.

Example

Example demonstrates writing HTTP error responses.

package main

import (
	"fmt"
	"net/http/httptest"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	err := errors.NewValidationError("email", "invalid format", "bad-email")

	// Create a test response recorder
	w := httptest.NewRecorder()

	// Write the error response
	errors.WriteHTTPError(w, err, "trace-xyz")

	fmt.Println("Status Code:", w.Code)
	fmt.Println("Content-Type:", w.Header().Get("Content-Type"))
}
Output:

Status Code: 400
Content-Type: application/json

Types

type BaseError

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

BaseError provides a foundation for all typed errors.

func (*BaseError) Code

func (e *BaseError) Code() string

Code returns the error code.

func (*BaseError) Error

func (e *BaseError) Error() string

Error implements the error interface.

func (*BaseError) Message

func (e *BaseError) Message() string

Message returns the error message.

func (*BaseError) Stack

func (e *BaseError) Stack() []uintptr

Stack returns the captured stack trace.

func (*BaseError) StackTrace

func (e *BaseError) StackTrace() string

StackTrace returns a formatted stack trace string.

func (*BaseError) Unwrap

func (e *BaseError) Unwrap() error

Unwrap returns the underlying cause.

type ConflictError

type ConflictError struct {
	*BaseError
	Resource string
	Field    string
	Value    string
}

ConflictError represents a resource conflict error.

func NewConflictError

func NewConflictError(resource, field, value string) *ConflictError

NewConflictError creates a new conflict error.

type Error

type Error interface {
	error
	// Code returns the error code
	Code() string
	// Message returns the human-readable error message
	Message() string
	// Unwrap returns the underlying cause
	Unwrap() error
}

Error is the base interface for all custom errors in the system. It extends the standard error interface with additional context.

type ErrorCategory

type ErrorCategory string

ErrorCategory represents a high-level error category.

const (
	// CategoryClient indicates a client-side error (4xx).
	CategoryClient ErrorCategory = "CLIENT_ERROR"

	// CategoryServer indicates a server-side error (5xx).
	CategoryServer ErrorCategory = "SERVER_ERROR"

	// CategoryNetwork indicates a network-related error.
	CategoryNetwork ErrorCategory = "NETWORK_ERROR"

	// CategoryTimeout indicates a timeout error.
	CategoryTimeout ErrorCategory = "TIMEOUT_ERROR"

	// CategoryValidation indicates a validation error.
	CategoryValidation ErrorCategory = "VALIDATION_ERROR"

	// CategoryAuth indicates an authentication/authorization error.
	CategoryAuth ErrorCategory = "AUTH_ERROR"
)

func GetCategory

func GetCategory(code string) ErrorCategory

GetCategory returns the category for an error code.

Example

Example demonstrates using error categories.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	code := errors.CodeNotFound
	category := errors.GetCategory(code)

	fmt.Println("Category:", category)
	fmt.Println("Is Client Error:", errors.IsClientError(code))
	fmt.Println("Is Server Error:", errors.IsServerError(code))
}
Output:

Category: CLIENT_ERROR
Is Client Error: true
Is Server Error: false

type ForbiddenError

type ForbiddenError struct {
	*BaseError
	Resource string
	Action   string
}

ForbiddenError represents an authorization error.

func NewForbiddenError

func NewForbiddenError(resource, action string) *ForbiddenError

NewForbiddenError creates a new forbidden error.

type HTTPError

type HTTPError struct {
	Status  int               `json:"-"`
	Code    string            `json:"code"`
	Message string            `json:"message"`
	Details map[string]string `json:"details,omitempty"`
	TraceID string            `json:"trace_id,omitempty"`
}

HTTPError represents an HTTP error response.

func ToHTTPError

func ToHTTPError(err error, traceID string) *HTTPError

ToHTTPError converts an error to an HTTPError.

Example

Example demonstrates converting errors to HTTP responses.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	err := errors.NewNotFoundError("user", "123")
	httpErr := errors.ToHTTPError(err, "trace-abc-123")

	fmt.Println("Status:", httpErr.Status)
	fmt.Println("Code:", httpErr.Code)
	fmt.Println("Message:", httpErr.Message)
	fmt.Println("Resource:", httpErr.Details["resource"])
}
Output:

Status: 404
Code: NOT_FOUND
Message: user not found
Resource: user

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface.

type InternalError

type InternalError struct {
	*BaseError
	Operation string
}

InternalError represents an internal server error.

func NewInternalError

func NewInternalError(message string, cause error) *InternalError

NewInternalError creates a new internal error.

Example

Example demonstrates creating internal errors with context.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	dbErr := fmt.Errorf("connection refused")
	err := errors.NewInternalError("failed to save user", dbErr).WithOperation("saveUser")

	fmt.Println("Message:", err.Message())
	fmt.Println("Operation:", err.Operation)
}
Output:

Message: failed to save user
Operation: saveUser

func (*InternalError) WithOperation

func (e *InternalError) WithOperation(op string) *InternalError

WithOperation sets the operation context.

type NotFoundError

type NotFoundError struct {
	*BaseError
	Resource string
	ID       string
}

NotFoundError represents a resource not found error.

func NewNotFoundError

func NewNotFoundError(resource, id string) *NotFoundError

NewNotFoundError creates a new not found error.

Example

Example demonstrates creating and using not found errors.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	err := errors.NewNotFoundError("user", "123")
	fmt.Println(err.Error())
	fmt.Println("HTTP Status:", errors.StatusCode(err))
}
Output:

user with ID '123' not found
HTTP Status: 404

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error implements the error interface.

type RateLimitError

type RateLimitError struct {
	*BaseError
	Limit      int
	RetryAfter int // seconds
}

RateLimitError represents a rate limiting error.

func NewRateLimitError

func NewRateLimitError(limit, retryAfter int) *RateLimitError

NewRateLimitError creates a new rate limit error.

type ServiceError

type ServiceError struct {
	*BaseError
	Service    string
	StatusCode int
}

ServiceError represents a downstream service error.

func NewServiceError

func NewServiceError(service, message string, statusCode int, cause error) *ServiceError

NewServiceError creates a new service error.

Example

Example demonstrates creating service errors.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	err := errors.NewServiceError("rqlite", "database unavailable", 503, nil)

	fmt.Println(err.Error())
	fmt.Println("Should Retry:", errors.ShouldRetry(err))
}
Output:

database unavailable
Should Retry: true

type TimeoutError

type TimeoutError struct {
	*BaseError
	Operation string
	Duration  string
}

TimeoutError represents a timeout error.

func NewTimeoutError

func NewTimeoutError(operation, duration string) *TimeoutError

NewTimeoutError creates a new timeout error.

type UnauthorizedError

type UnauthorizedError struct {
	*BaseError
	Realm string
}

UnauthorizedError represents an authentication error.

func NewUnauthorizedError

func NewUnauthorizedError(message string) *UnauthorizedError

NewUnauthorizedError creates a new unauthorized error.

func (*UnauthorizedError) WithRealm

func (e *UnauthorizedError) WithRealm(realm string) *UnauthorizedError

WithRealm sets the authentication realm.

type ValidationError

type ValidationError struct {
	*BaseError
	Field string
	Value interface{}
}

ValidationError represents an input validation error.

func NewValidationError

func NewValidationError(field, message string, value interface{}) *ValidationError

NewValidationError creates a new validation error.

Example

Example demonstrates creating and using validation errors.

package main

import (
	"fmt"

	"github.com/DeBrosOfficial/network/pkg/errors"
)

func main() {
	err := errors.NewValidationError("email", "invalid email format", "not-an-email")
	fmt.Println(err.Error())
	fmt.Println("Code:", err.Code())
}
Output:

validation error: email: invalid email format
Code: VALIDATION_ERROR

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

Jump to

Keyboard shortcuts

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