errors

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package errors defines custom error types and sentinel errors for the gdl download library.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidURL is returned when a provided URL is malformed or invalid.
	ErrInvalidURL = errors.New("invalid URL provided")

	// ErrFileExists is returned when attempting to download to a file that already exists
	// and overwrite is not enabled.
	ErrFileExists = errors.New("file already exists")

	// ErrInsufficientSpace is returned when there is not enough disk space to complete
	// the download operation.
	ErrInsufficientSpace = errors.New("insufficient disk space")

	// ErrNetworkError is returned for general network-related errors during download.
	ErrNetworkError = errors.New("network error occurred")
)

Sentinel errors for common download scenarios. These can be used with errors.Is() for error comparison.

Functions

func IsRetryable

func IsRetryable(err error) bool

IsRetryable is a convenience function to check if any error is retryable.

Types

type AdaptiveRetryStrategy

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

AdaptiveRetryStrategy implements adaptive retry with backoff based on error patterns.

func NewAdaptiveRetryStrategy

func NewAdaptiveRetryStrategy(base *RetryStrategy) *AdaptiveRetryStrategy

NewAdaptiveRetryStrategy creates a new adaptive retry strategy.

func (*AdaptiveRetryStrategy) GetAdjustedDelay

func (ars *AdaptiveRetryStrategy) GetAdjustedDelay(baseDelay time.Duration) time.Duration

GetAdjustedDelay returns the adjusted delay based on adaptive multiplier.

func (*AdaptiveRetryStrategy) UpdateStrategy

func (ars *AdaptiveRetryStrategy) UpdateStrategy(err error)

UpdateStrategy updates the strategy based on error patterns.

type CircuitBreaker

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

CircuitBreaker implements a circuit breaker pattern for retry logic.

func NewCircuitBreaker

func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker.

func (*CircuitBreaker) Call

func (cb *CircuitBreaker) Call(fn func() error) error

Call executes a function through the circuit breaker.

type CircuitState

type CircuitState int

CircuitState represents the state of a circuit breaker.

const (
	CircuitClosed CircuitState = iota
	CircuitOpen
	CircuitHalfOpen
)

type DownloadError

type DownloadError struct {
	// Code represents the type of error that occurred.
	Code ErrorCode

	// Message is a user-friendly error message that can be displayed to end users.
	Message string

	// Details contains technical details about the error for debugging purposes.
	Details string

	// URL is the source URL that caused the error, if applicable.
	URL string

	// Filename is the target filename that was being written to, if applicable.
	Filename string

	// Underlying is the original error that caused this download error.
	Underlying error

	// Retryable indicates whether this error condition might succeed if retried.
	Retryable bool

	// HTTPStatusCode contains the HTTP status code if the error is HTTP-related.
	HTTPStatusCode int

	// BytesTransferred indicates how many bytes were successfully transferred
	// before the error occurred.
	BytesTransferred int64
}

DownloadError represents a structured error that occurs during download operations. It provides detailed information about what went wrong, including user-friendly messages and technical details for debugging.

func FromHTTPStatus

func FromHTTPStatus(statusCode int, url string) *DownloadError

FromHTTPStatus creates a DownloadError based on an HTTP status code.

func NewDownloadError

func NewDownloadError(code ErrorCode, message string) *DownloadError

NewDownloadError creates a new DownloadError with the specified code and message.

func NewDownloadErrorWithDetails

func NewDownloadErrorWithDetails(code ErrorCode, message, details string) *DownloadError

NewDownloadErrorWithDetails creates a new DownloadError with code, message, and technical details.

func WrapError

func WrapError(underlying error, code ErrorCode, message string) *DownloadError

WrapError wraps an existing error as a DownloadError with additional context.

func WrapErrorWithURL

func WrapErrorWithURL(underlying error, code ErrorCode, message, url string) *DownloadError

WrapErrorWithURL wraps an existing error as a DownloadError with URL context.

func (*DownloadError) Error

func (e *DownloadError) Error() string

Error implements the error interface for DownloadError.

func (*DownloadError) Is

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

Is implements error comparison for DownloadError. This allows checking if a DownloadError wraps a specific sentinel error.

func (*DownloadError) Unwrap

func (e *DownloadError) Unwrap() error

Unwrap returns the underlying error for error unwrapping support. This allows the use of errors.Is() and errors.As() with DownloadError.

type ErrorCode

type ErrorCode int
const (
	// CodeUnknown represents an unknown or unclassified error.
	CodeUnknown ErrorCode = iota

	// CodeInvalidURL represents errors related to malformed or invalid URLs.
	CodeInvalidURL

	// CodeFileExists represents errors when target file already exists.
	CodeFileExists

	// CodeInsufficientSpace represents errors due to lack of disk space.
	CodeInsufficientSpace

	// CodeNetworkError represents network-related errors.
	CodeNetworkError

	// CodeTimeout represents timeout errors during download.
	CodeTimeout

	// CodePermissionDenied represents permission-related errors.
	CodePermissionDenied

	// CodeFileNotFound represents errors when source file is not found.
	CodeFileNotFound

	// CodeAuthenticationFailed represents authentication or authorization errors.
	CodeAuthenticationFailed

	// CodeServerError represents server-side errors (5xx HTTP status codes).
	CodeServerError

	// CodeClientError represents client-side errors (4xx HTTP status codes).
	CodeClientError

	// CodeCancelled represents errors when download is cancelled by user.
	CodeCancelled

	// CodeCorruptedData represents errors when downloaded data is corrupted.
	CodeCorruptedData
)

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode extracts the error code from any error, returning CodeUnknown if the error is not a DownloadError.

func (ErrorCode) String

func (c ErrorCode) String() string

String returns a string representation of the error code.

type ErrorCodeRegistry

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

ErrorCodeRegistry provides centralized error code management.

func NewErrorCodeRegistry

func NewErrorCodeRegistry() *ErrorCodeRegistry

NewErrorCodeRegistry creates a new error code registry with predefined mappings.

func (*ErrorCodeRegistry) GetFileSystemCodeMessage

func (r *ErrorCodeRegistry) GetFileSystemCodeMessage(code FileSystemErrorCode) string

GetFileSystemCodeMessage returns the message for a file system error code.

func (*ErrorCodeRegistry) GetHTTPCodeFromStatus

func (r *ErrorCodeRegistry) GetHTTPCodeFromStatus(statusCode int) HTTPErrorCode

GetHTTPCodeFromStatus converts HTTP status code to HTTPErrorCode.

func (*ErrorCodeRegistry) GetHTTPCodeMessage

func (r *ErrorCodeRegistry) GetHTTPCodeMessage(code HTTPErrorCode) string

GetHTTPCodeMessage returns the message for an HTTP error code.

func (*ErrorCodeRegistry) GetNetworkCodeMessage

func (r *ErrorCodeRegistry) GetNetworkCodeMessage(code NetworkErrorCode) string

GetNetworkCodeMessage returns the message for a network error code.

func (*ErrorCodeRegistry) GetValidationCodeMessage

func (r *ErrorCodeRegistry) GetValidationCodeMessage(code ValidationErrorCode) string

GetValidationCodeMessage returns the message for a validation error code.

func (*ErrorCodeRegistry) IsRetryableHTTPCode

func (r *ErrorCodeRegistry) IsRetryableHTTPCode(code HTTPErrorCode) bool

IsRetryableHTTPCode determines if an HTTP error code is retryable.

func (*ErrorCodeRegistry) IsRetryableNetworkCode

func (r *ErrorCodeRegistry) IsRetryableNetworkCode(code NetworkErrorCode) bool

IsRetryableNetworkCode determines if a network error code is retryable.

type ErrorHandler

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

ErrorHandler provides utilities for error handling and formatting.

func NewErrorHandler

func NewErrorHandler(verbose bool) *ErrorHandler

NewErrorHandler creates a new error handler.

func (*ErrorHandler) AggregateErrors

func (h *ErrorHandler) AggregateErrors(errors []error) error

AggregateErrors combines multiple errors into a single error message.

func (*ErrorHandler) FormatError

func (h *ErrorHandler) FormatError(err error) string

FormatError formats an error for display to the user.

func (*ErrorHandler) HandleError

func (h *ErrorHandler) HandleError(err error, context string) *DownloadError

HandleError processes an error and returns a DownloadError.

type FileSystemErrorCode

type FileSystemErrorCode string

FileSystemErrorCode represents file system-related error codes.

const (
	// Permission errors.
	FSPermissionDenied       FileSystemErrorCode = "FS_PERMISSION_DENIED"
	FSAccessDenied           FileSystemErrorCode = "FS_ACCESS_DENIED"
	FSReadOnlyFilesystem     FileSystemErrorCode = "FS_READ_ONLY"
	FSInsufficientPrivileges FileSystemErrorCode = "FS_INSUFFICIENT_PRIVILEGES"

	// Space errors.
	FSInsufficientSpace FileSystemErrorCode = "FS_INSUFFICIENT_SPACE"
	FSQuotaExceeded     FileSystemErrorCode = "FS_QUOTA_EXCEEDED"
	FSDeviceFull        FileSystemErrorCode = "FS_DEVICE_FULL"
	FSInodeExhausted    FileSystemErrorCode = "FS_INODE_EXHAUSTED"

	// File/Directory errors.
	FSFileNotFound      FileSystemErrorCode = "FS_FILE_NOT_FOUND"
	FSDirectoryNotFound FileSystemErrorCode = "FS_DIRECTORY_NOT_FOUND"
	FSFileExists        FileSystemErrorCode = "FS_FILE_EXISTS"
	FSDirectoryExists   FileSystemErrorCode = "FS_DIRECTORY_EXISTS"
	FSIsDirectory       FileSystemErrorCode = "FS_IS_DIRECTORY"
	FSNotDirectory      FileSystemErrorCode = "FS_NOT_DIRECTORY"
	FSDirectoryNotEmpty FileSystemErrorCode = "FS_DIRECTORY_NOT_EMPTY"

	// I/O errors.
	FSIOError    FileSystemErrorCode = "FS_IO_ERROR"
	FSReadError  FileSystemErrorCode = "FS_READ_ERROR"
	FSWriteError FileSystemErrorCode = "FS_WRITE_ERROR"
	FSSeekError  FileSystemErrorCode = "FS_SEEK_ERROR"
	FSFlushError FileSystemErrorCode = "FS_FLUSH_ERROR"

	// Corruption errors.
	FSCorruptedFile     FileSystemErrorCode = "FS_CORRUPTED_FILE"
	FSChecksumMismatch  FileSystemErrorCode = "FS_CHECKSUM_MISMATCH"
	FSUnexpectedEOF     FileSystemErrorCode = "FS_UNEXPECTED_EOF"
	FSBadFileDescriptor FileSystemErrorCode = "FS_BAD_FILE_DESCRIPTOR"

	// Device errors.
	FSDeviceNotReady FileSystemErrorCode = "FS_DEVICE_NOT_READY"
	FSDeviceError    FileSystemErrorCode = "FS_DEVICE_ERROR"
	FSNetworkDrive   FileSystemErrorCode = "FS_NETWORK_DRIVE_ERROR"
	FSRemoteIOError  FileSystemErrorCode = "FS_REMOTE_IO_ERROR"

	// Lock errors.
	FSFileLocked       FileSystemErrorCode = "FS_FILE_LOCKED"
	FSLockViolation    FileSystemErrorCode = "FS_LOCK_VIOLATION"
	FSSharingViolation FileSystemErrorCode = "FS_SHARING_VIOLATION"
)

type HTTPErrorCode

type HTTPErrorCode string

HTTPErrorCode represents HTTP-related error codes.

const (
	// 4xx Client Errors.
	HTTPBadRequest           HTTPErrorCode = "HTTP_400_BAD_REQUEST"
	HTTPUnauthorized         HTTPErrorCode = "HTTP_401_UNAUTHORIZED"
	HTTPPaymentRequired      HTTPErrorCode = "HTTP_402_PAYMENT_REQUIRED"
	HTTPForbidden            HTTPErrorCode = "HTTP_403_FORBIDDEN"
	HTTPNotFound             HTTPErrorCode = "HTTP_404_NOT_FOUND"
	HTTPMethodNotAllowed     HTTPErrorCode = "HTTP_405_METHOD_NOT_ALLOWED"
	HTTPNotAcceptable        HTTPErrorCode = "HTTP_406_NOT_ACCEPTABLE"
	HTTPProxyAuthRequired    HTTPErrorCode = "HTTP_407_PROXY_AUTH_REQUIRED"
	HTTPRequestTimeout       HTTPErrorCode = "HTTP_408_REQUEST_TIMEOUT"
	HTTPConflict             HTTPErrorCode = "HTTP_409_CONFLICT"
	HTTPGone                 HTTPErrorCode = "HTTP_410_GONE"
	HTTPLengthRequired       HTTPErrorCode = "HTTP_411_LENGTH_REQUIRED"
	HTTPPreconditionFailed   HTTPErrorCode = "HTTP_412_PRECONDITION_FAILED"
	HTTPPayloadTooLarge      HTTPErrorCode = "HTTP_413_PAYLOAD_TOO_LARGE"
	HTTPURITooLong           HTTPErrorCode = "HTTP_414_URI_TOO_LONG"
	HTTPUnsupportedMediaType HTTPErrorCode = "HTTP_415_UNSUPPORTED_MEDIA_TYPE"
	HTTPRangeNotSatisfiable  HTTPErrorCode = "HTTP_416_RANGE_NOT_SATISFIABLE"
	HTTPExpectationFailed    HTTPErrorCode = "HTTP_417_EXPECTATION_FAILED"
	HTTPTooManyRequests      HTTPErrorCode = "HTTP_429_TOO_MANY_REQUESTS"

	// 5xx Server Errors.
	HTTPInternalServerError HTTPErrorCode = "HTTP_500_INTERNAL_SERVER_ERROR"
	HTTPNotImplemented      HTTPErrorCode = "HTTP_501_NOT_IMPLEMENTED"
	HTTPBadGateway          HTTPErrorCode = "HTTP_502_BAD_GATEWAY"
	HTTPServiceUnavailable  HTTPErrorCode = "HTTP_503_SERVICE_UNAVAILABLE"
	HTTPGatewayTimeout      HTTPErrorCode = "HTTP_504_GATEWAY_TIMEOUT"
	HTTPVersionNotSupported HTTPErrorCode = "HTTP_505_VERSION_NOT_SUPPORTED"
	HTTPInsufficientStorage HTTPErrorCode = "HTTP_507_INSUFFICIENT_STORAGE"
	HTTPLoopDetected        HTTPErrorCode = "HTTP_508_LOOP_DETECTED"
	HTTPNotExtended         HTTPErrorCode = "HTTP_510_NOT_EXTENDED"
	HTTPNetworkAuthRequired HTTPErrorCode = "HTTP_511_NETWORK_AUTH_REQUIRED"
)

type NetworkErrorCode

type NetworkErrorCode string

NetworkErrorCode represents network-related error codes.

const (
	// DNS-related errors.
	NetworkDNSNotFound NetworkErrorCode = "DNS_NOT_FOUND"
	NetworkDNSTimeout  NetworkErrorCode = "DNS_TIMEOUT"
	NetworkDNSFailure  NetworkErrorCode = "DNS_FAILURE"

	// Connection errors.
	NetworkConnectionRefused  NetworkErrorCode = "CONNECTION_REFUSED"
	NetworkConnectionTimeout  NetworkErrorCode = "CONNECTION_TIMEOUT"
	NetworkConnectionReset    NetworkErrorCode = "CONNECTION_RESET"
	NetworkConnectionAborted  NetworkErrorCode = "CONNECTION_ABORTED"
	NetworkHostUnreachable    NetworkErrorCode = "HOST_UNREACHABLE"
	NetworkNetworkUnreachable NetworkErrorCode = "NETWORK_UNREACHABLE"

	// Protocol errors.
	NetworkTLSHandshakeFailure NetworkErrorCode = "TLS_HANDSHAKE_FAILURE"
	NetworkProtocolError       NetworkErrorCode = "PROTOCOL_ERROR"
	NetworkProxyError          NetworkErrorCode = "PROXY_ERROR"

	// Timeout errors.
	NetworkReadTimeout    NetworkErrorCode = "READ_TIMEOUT"
	NetworkWriteTimeout   NetworkErrorCode = "WRITE_TIMEOUT"
	NetworkRequestTimeout NetworkErrorCode = "REQUEST_TIMEOUT"
)

type RetryManager

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

RetryManager handles retry logic.

func NewRetryManager

func NewRetryManager(strategy *RetryStrategy) *RetryManager

NewRetryManager creates a new retry manager.

func (*RetryManager) Execute

func (rm *RetryManager) Execute(ctx context.Context, operation func() error) error

Execute runs the given function with retry logic.

type RetryStrategy

type RetryStrategy struct {
	MaxAttempts    int
	InitialDelay   time.Duration
	MaxDelay       time.Duration
	Multiplier     float64
	Jitter         bool
	RetryCondition func(error) bool
	OnRetry        func(attempt int, err error, nextDelay time.Duration)
}

RetryStrategy defines the retry behavior.

func DefaultRetryStrategy

func DefaultRetryStrategy() *RetryStrategy

DefaultRetryStrategy returns a default retry strategy.

func ExponentialBackoffStrategy

func ExponentialBackoffStrategy(maxAttempts int) *RetryStrategy

ExponentialBackoffStrategy returns an exponential backoff strategy.

type Suggestion

type Suggestion struct {
	Summary    string   `json:"summary"`
	Steps      []string `json:"steps"`
	Tips       []string `json:"tips,omitempty"`
	DocLinks   []string `json:"doc_links,omitempty"`
	Examples   []string `json:"examples,omitempty"`
	References []string `json:"references,omitempty"`
}

Suggestion represents a user-friendly suggestion with recovery steps.

type SuggestionProvider

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

SuggestionProvider provides user-friendly recovery suggestions for different error types.

func NewSuggestionProvider

func NewSuggestionProvider() *SuggestionProvider

NewSuggestionProvider creates a new suggestion provider.

func (*SuggestionProvider) FormatSuggestion

func (sp *SuggestionProvider) FormatSuggestion(suggestion *Suggestion) string

FormatSuggestion formats a suggestion for display to the user.

func (*SuggestionProvider) GetQuickFixes

func (sp *SuggestionProvider) GetQuickFixes() map[string]string

GetQuickFixes returns common quick fixes for download problems.

func (*SuggestionProvider) GetSuggestion

func (sp *SuggestionProvider) GetSuggestion(code ErrorCode) *Suggestion

GetSuggestion returns a comprehensive suggestion for the given error code.

func (*SuggestionProvider) GetSuggestionForError

func (sp *SuggestionProvider) GetSuggestionForError(err error) *Suggestion

GetSuggestionForError returns a suggestion based on the error type and context.

func (*SuggestionProvider) GetTroubleshootingSteps

func (sp *SuggestionProvider) GetTroubleshootingSteps() []string

GetTroubleshootingSteps returns general troubleshooting steps for download issues.

type ValidationErrorCode

type ValidationErrorCode string

ValidationErrorCode represents validation-related error codes.

const (
	// URL validation errors.
	ValidationInvalidURL        ValidationErrorCode = "VALIDATION_INVALID_URL"
	ValidationUnsupportedScheme ValidationErrorCode = "VALIDATION_UNSUPPORTED_SCHEME"
	ValidationMalformedURL      ValidationErrorCode = "VALIDATION_MALFORMED_URL"
	ValidationEmptyURL          ValidationErrorCode = "VALIDATION_EMPTY_URL"
	ValidationURLTooLong        ValidationErrorCode = "VALIDATION_URL_TOO_LONG"
	ValidationInvalidDomain     ValidationErrorCode = "VALIDATION_INVALID_DOMAIN"
	ValidationInvalidPort       ValidationErrorCode = "VALIDATION_INVALID_PORT"

	// File format validation errors.
	ValidationInvalidFileFormat ValidationErrorCode = "VALIDATION_INVALID_FILE_FORMAT"
	ValidationUnsupportedFormat ValidationErrorCode = "VALIDATION_UNSUPPORTED_FORMAT"
	ValidationCorruptedHeader   ValidationErrorCode = "VALIDATION_CORRUPTED_HEADER"
	ValidationInvalidMimeType   ValidationErrorCode = "VALIDATION_INVALID_MIME_TYPE"
	ValidationFileSizeMismatch  ValidationErrorCode = "VALIDATION_FILE_SIZE_MISMATCH"
	ValidationInvalidChecksum   ValidationErrorCode = "VALIDATION_INVALID_CHECKSUM"

	// Parameter validation errors.
	ValidationInvalidParameter  ValidationErrorCode = "VALIDATION_INVALID_PARAMETER"
	ValidationMissingParameter  ValidationErrorCode = "VALIDATION_MISSING_PARAMETER"
	ValidationParameterTooLarge ValidationErrorCode = "VALIDATION_PARAMETER_TOO_LARGE"
	ValidationParameterTooSmall ValidationErrorCode = "VALIDATION_PARAMETER_TOO_SMALL"
	ValidationInvalidRange      ValidationErrorCode = "VALIDATION_INVALID_RANGE"
	ValidationInvalidFormat     ValidationErrorCode = "VALIDATION_INVALID_FORMAT"

	// Configuration validation errors.
	ValidationInvalidConfig  ValidationErrorCode = "VALIDATION_INVALID_CONFIG"
	ValidationMissingConfig  ValidationErrorCode = "VALIDATION_MISSING_CONFIG"
	ValidationConfigConflict ValidationErrorCode = "VALIDATION_CONFIG_CONFLICT"
)

Jump to

Keyboard shortcuts

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