Documentation
¶
Index ¶
- Constants
- Variables
- func Cause(err error) error
- func GetErrorCode(err error) string
- func GetErrorMessage(err error) string
- func HTTPStatusToCode(status int) string
- func IsClientError(code string) bool
- func IsConflict(err error) bool
- func IsForbidden(err error) bool
- func IsInternal(err error) bool
- func IsNotFound(err error) bool
- func IsRateLimit(err error) bool
- func IsRetryable(code string) bool
- func IsServerError(code string) bool
- func IsServiceUnavailable(err error) bool
- func IsTimeout(err error) bool
- func IsUnauthorized(err error) bool
- func IsValidation(err error) bool
- func New(message string) error
- func Newf(format string, args ...interface{}) error
- func ShouldRetry(err error) bool
- func StatusCode(err error) int
- func Wrap(err error, message string) error
- func Wrapf(err error, format string, args ...interface{}) error
- func WriteHTTPError(w http.ResponseWriter, err error, traceID string)
- type BaseError
- type ConflictError
- type Error
- type ErrorCategory
- type ForbiddenError
- type HTTPError
- type InternalError
- type NotFoundError
- type RateLimitError
- type ServiceError
- type TimeoutError
- type UnauthorizedError
- type ValidationError
Examples ¶
Constants ¶
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 = "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 = "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 = "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 ¶
var ( // ErrNotFound is returned when a resource is not found. ErrNotFound = errors.New("not found") 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 = 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 ¶
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 ¶
GetErrorCode extracts the error code from an error.
func GetErrorMessage ¶
GetErrorMessage extracts a human-readable message from an error.
func HTTPStatusToCode ¶
HTTPStatusToCode converts an HTTP status code to an error code.
func IsClientError ¶
IsClientError returns true if the error is a client error (4xx).
func IsConflict ¶
IsConflict checks if an error indicates a resource conflict.
func IsForbidden ¶
IsForbidden checks if an error indicates lack of authorization.
func IsInternal ¶
IsInternal checks if an error is an internal error.
func IsNotFound ¶
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 ¶
IsRateLimit checks if an error indicates rate limiting.
func IsRetryable ¶
IsRetryable returns true if an error with the given code should be retried.
func IsServerError ¶
IsServerError returns true if the error is a server error (5xx).
func IsServiceUnavailable ¶
IsServiceUnavailable checks if an error indicates a service is unavailable.
func IsUnauthorized ¶
IsUnauthorized checks if an error indicates lack of authentication.
func IsValidation ¶
IsValidation checks if an error is a validation error.
func ShouldRetry ¶
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 ¶
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 ¶
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 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) StackTrace ¶
StackTrace returns a formatted stack trace string.
type ConflictError ¶
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 ¶
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 ¶
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
type InternalError ¶
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 ¶
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 ¶
RateLimitError represents a rate limiting error.
func NewRateLimitError ¶
func NewRateLimitError(limit, retryAfter int) *RateLimitError
NewRateLimitError creates a new rate limit error.
type ServiceError ¶
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 ¶
TimeoutError represents a timeout error.
func NewTimeoutError ¶
func NewTimeoutError(operation, duration string) *TimeoutError
NewTimeoutError creates a new timeout error.
type UnauthorizedError ¶
type UnauthorizedError struct {
}
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 ¶
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.