/** * @db4/core - Error Types * * Error classes and error handling utilities for the db4 ecosystem. * * @packageDocumentation */ import type { ConflictInfo } from './types.js'; /** * High-level error categories for error handling decisions. */ export declare enum ErrorCategory { /** Validation errors - bad input, schema violations */ VALIDATION = "VALIDATION", /** Conflict errors - concurrent modifications, optimistic locking failures */ CONFLICT = "CONFLICT", /** Timeout errors - operation exceeded time limit */ TIMEOUT = "TIMEOUT", /** Not found errors - requested resource doesn't exist */ NOT_FOUND = "NOT_FOUND", /** Capacity errors - resource limits exceeded */ CAPACITY = "CAPACITY", /** Configuration errors - invalid settings */ CONFIGURATION = "CONFIGURATION", /** Transient errors - temporary failures that may succeed on retry */ TRANSIENT = "TRANSIENT", /** Internal errors - unexpected system failures */ INTERNAL = "INTERNAL", /** Network errors - connectivity issues, timeouts */ NETWORK = "NETWORK", /** Authentication errors - unauthorized, forbidden, token issues */ AUTHENTICATION = "AUTHENTICATION" } /** * Retry strategy recommendations for error handling. */ export interface RetryGuidance { /** Whether the operation should be retried */ retryable: boolean; /** Suggested delay before retry in milliseconds */ suggestedDelayMs?: number; /** Maximum number of retry attempts recommended */ maxRetries?: number; /** Whether to use exponential backoff */ useExponentialBackoff?: boolean; /** Backoff multiplier for exponential backoff */ backoffMultiplier?: number; /** Maximum delay cap in milliseconds */ maxDelayMs?: number; /** Specific actions that may help resolve the error */ resolutionHints?: string[]; } /** * Default retry guidance for each error category. */ export declare const DEFAULT_RETRY_GUIDANCE: Record; /** * Error codes for categorizing errors. * * Error codes follow the pattern: `{DOMAIN}_{TYPE}` where: * - Domain: The area (DOCUMENT, QUERY, TRANSACTION, etc.) * - Type: The kind of error (NOT_FOUND, TIMEOUT, INVALID, etc.) * * @example * ```typescript * // Check error code * if (error.code === ErrorCode.DOCUMENT_NOT_FOUND) { * // Handle missing document * } * ``` */ export declare enum ErrorCode { /** Requested document does not exist */ DOCUMENT_NOT_FOUND = "DOCUMENT_NOT_FOUND", /** Document exceeds maximum size limit */ DOCUMENT_TOO_LARGE = "DOCUMENT_TOO_LARGE", /** Document structure or content is invalid */ DOCUMENT_INVALID = "DOCUMENT_INVALID", /** Requested batch does not exist */ BATCH_NOT_FOUND = "BATCH_NOT_FOUND", /** Batch exceeds maximum capacity */ BATCH_OVERFLOW = "BATCH_OVERFLOW", /** Document violates schema constraints */ SCHEMA_VIOLATION = "SCHEMA_VIOLATION", /** Referenced schema does not exist */ SCHEMA_NOT_FOUND = "SCHEMA_NOT_FOUND", /** Referenced index does not exist */ INDEX_NOT_FOUND = "INDEX_NOT_FOUND", /** Unique constraint violated by duplicate key */ DUPLICATE_KEY = "DUPLICATE_KEY", /** Query syntax or structure is invalid */ INVALID_QUERY = "INVALID_QUERY", /** Query execution exceeded time limit */ QUERY_TIMEOUT = "QUERY_TIMEOUT", /** SQL injection attempt detected */ SQL_INJECTION = "SQL_INJECTION", /** Input data is invalid */ INVALID_INPUT = "INVALID_INPUT", /** Validation rules not satisfied */ VALIDATION_ERROR = "VALIDATION_ERROR", /** General transaction error */ TRANSACTION_ERROR = "TRANSACTION_ERROR", /** Concurrent modification conflict */ TRANSACTION_CONFLICT = "TRANSACTION_CONFLICT", /** Transaction exceeded time limit */ TRANSACTION_TIMEOUT = "TRANSACTION_TIMEOUT", /** Referential integrity constraint violated */ REFERENTIAL_INTEGRITY = "REFERENTIAL_INTEGRITY", /** Foreign key constraint violated */ FOREIGN_KEY_VIOLATION = "FOREIGN_KEY_VIOLATION", /** Memory limit exceeded */ MEMORY_LIMIT_EXCEEDED = "MEMORY_LIMIT_EXCEEDED", /** Storage limit exceeded */ STORAGE_LIMIT_EXCEEDED = "STORAGE_LIMIT_EXCEEDED", /** Configuration is invalid */ INVALID_CONFIG = "INVALID_CONFIG", /** Requested shard does not exist */ SHARD_NOT_FOUND = "SHARD_NOT_FOUND", /** Shard routing failed */ SHARD_ROUTING_ERROR = "SHARD_ROUTING_ERROR", /** Change data capture error */ CDC_ERROR = "CDC_ERROR", /** Cursor format or content is invalid */ CURSOR_INVALID = "CURSOR_INVALID", /** Cursor has expired */ CURSOR_EXPIRED = "CURSOR_EXPIRED", /** Session not found */ SESSION_NOT_FOUND = "SESSION_NOT_FOUND", /** Session has expired */ SESSION_EXPIRED = "SESSION_EXPIRED", /** JWT token has expired */ JWT_EXPIRED = "JWT_EXPIRED", /** JWT token is invalid */ JWT_INVALID = "JWT_INVALID", /** Request is unauthorized - missing or invalid credentials */ UNAUTHORIZED = "UNAUTHORIZED", /** Request is forbidden - insufficient permissions */ FORBIDDEN = "FORBIDDEN", /** Authentication token has expired and needs refresh */ TOKEN_EXPIRED = "TOKEN_EXPIRED", /** General network error */ NETWORK_ERROR = "NETWORK_ERROR", /** Network request timed out */ NETWORK_TIMEOUT = "NETWORK_TIMEOUT", /** Failed to establish connection */ CONNECTION_FAILED = "CONNECTION_FAILED", /** Rate limit exceeded */ RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED", /** Sandbox execution failed */ SANDBOX_EXECUTION = "SANDBOX_EXECUTION", /** Sandbox security violation */ SANDBOX_SECURITY = "SANDBOX_SECURITY", /** Sandbox timeout exceeded */ SANDBOX_TIMEOUT = "SANDBOX_TIMEOUT", /** Sandbox memory limit exceeded */ SANDBOX_MEMORY = "SANDBOX_MEMORY", /** Magic map resolution failed */ MAGIC_MAP_RESOLUTION = "MAGIC_MAP_RESOLUTION", /** Unexpected internal error */ INTERNAL_ERROR = "INTERNAL_ERROR", /** All batch operations failed */ BATCH_OPERATION_ERROR = "BATCH_OPERATION_ERROR", /** Some batch operations failed */ PARTIAL_BATCH_FAILURE = "PARTIAL_BATCH_FAILURE" } /** * Maps error codes to their categories for classification. * * This mapping determines: * - Whether an error is retryable * - What retry strategy to use * - How to handle the error in error boundaries */ export declare const ERROR_CODE_TO_CATEGORY: Record; /** * Gets the category for an error code. */ export declare function getErrorCategory(code: ErrorCode): ErrorCategory; /** * Gets the default retry guidance for an error code. */ export declare function getRetryGuidance(code: ErrorCode): RetryGuidance; /** * Base error class for all db4 errors. * * Provides structured error information with: * - `code`: A specific error code for programmatic handling * - `category`: High-level category for error handling decisions * - `details`: Additional context about the error * - `retryGuidance`: Recommendations for retry behavior * * All error classes in db4 extend this base class following the naming convention: * `{Domain}{Type}Error` (e.g., `DocumentNotFoundError`, `QueryTimeoutError`) * * @example * ```typescript * try { * await db.get('users', 'non-existent-id'); * } catch (error) { * if (error instanceof DB4Error) { * console.log(error.code); // 'DOCUMENT_NOT_FOUND' * console.log(error.category); // 'NOT_FOUND' * console.log(error.isRetryable); // false * } * } * ``` */ export declare class DB4Error extends Error { /** * Error code for categorization and handling. */ readonly code: ErrorCode; /** * High-level error category for handling decisions. */ readonly category: ErrorCategory; /** * Additional details about the error. */ readonly details: Record | undefined; /** * Timestamp when the error occurred. */ readonly timestamp: number; /** * Retry guidance for this error (internal storage). */ protected readonly _retryGuidance: RetryGuidance; constructor(code: ErrorCode, message: string, details?: Record); /** * Retry guidance for this error. */ get retryGuidance(): RetryGuidance; /** * Whether this error can be retried. */ get isRetryable(): boolean; /** * Converts the error to a plain object for serialization. */ toJSON(): Record; /** * Creates a DB4Error from a plain object. */ static fromJSON(json: Record): DB4Error; } /** * Error thrown when a document is not found. */ export declare class DocumentNotFoundError extends DB4Error { readonly collection: string; readonly documentId: string; constructor(collection: string, documentId: string); } /** * Error thrown when a document exceeds size limits. */ export declare class DocumentTooLargeError extends DB4Error { constructor(size: number, limit: number); } /** * Error thrown when memory limit is exceeded. */ export declare class MemoryLimitExceededError extends DB4Error { constructor(size: number, limit: number); } /** * Write-write conflict error for optimistic concurrency control. */ export declare class ConflictError extends DB4Error { /** * List of documents that had version conflicts. */ readonly conflicts: ConflictInfo[]; constructor(conflicts: ConflictInfo[]); } /** * Error thrown when a transaction times out. */ export declare class TransactionTimeoutError extends DB4Error { constructor(transactionId: string, timeout: number); } /** * Validation error with detailed field information. */ export declare class ValidationError extends DB4Error { readonly field?: string | undefined; readonly value?: unknown | undefined; constructor(message: string, field?: string | undefined, value?: unknown | undefined); } /** * Error thrown when schema validation fails. */ export declare class SchemaValidationError extends DB4Error { readonly schemaName: string; readonly violations: Array<{ field: string; message: string; }>; constructor(message: string, schemaName: string, violations: Array<{ field: string; message: string; }>); } /** * Error thrown when a query is invalid. */ export declare class InvalidQueryError extends DB4Error { constructor(message: string, details?: Record); } /** * Error thrown when a query times out. */ export declare class QueryTimeoutError extends DB4Error { constructor(timeout: number); } /** * Cursor error codes. */ export declare enum CursorErrorCode { INVALID_FORMAT = "INVALID_FORMAT", MISSING_FIELDS = "MISSING_FIELDS", EXPIRED = "EXPIRED", VERSION_MISMATCH = "VERSION_MISMATCH", TAMPERED = "TAMPERED" } /** * Error thrown when a cursor is invalid. */ export declare class CursorError extends DB4Error { readonly cursorErrorCode: CursorErrorCode; constructor(code: CursorErrorCode, message: string); } /** * Error thrown when a shard is not found. */ export declare class ShardNotFoundError extends DB4Error { constructor(shardId: string); } /** * Error thrown when shard routing fails. */ export declare class ShardRoutingError extends DB4Error { constructor(message: string, context?: Record); } /** * Error thrown when configuration is invalid. */ export declare class InvalidConfigError extends DB4Error { constructor(message: string, configKey?: string); } /** * Network error codes for more specific network error handling. */ export declare enum NetworkErrorCode { /** General network error */ NETWORK_ERROR = "NETWORK_ERROR", /** Network request timed out */ TIMEOUT = "TIMEOUT", /** Failed to establish connection */ CONNECTION_FAILED = "CONNECTION_FAILED" } /** * Error thrown when a network operation fails. * * NetworkError covers connectivity issues, timeouts, and connection failures. * These errors are typically retryable with exponential backoff. * * @example * ```typescript * try { * await fetch(url); * } catch (error) { * throw new NetworkError(NetworkErrorCode.CONNECTION_FAILED, 'Failed to connect to server'); * } * ``` */ export declare class NetworkError extends DB4Error { /** * Specific network error code for programmatic handling. */ readonly networkErrorCode: NetworkErrorCode; /** * The URL or endpoint that failed, if available. */ readonly endpoint?: string; /** * The HTTP status code, if available. */ readonly statusCode?: number; constructor(code: NetworkErrorCode, message: string, options?: { endpoint?: string; statusCode?: number; cause?: Error; }); /** * Creates a NetworkError for a timeout. */ static timeout(message: string, endpoint?: string): NetworkError; /** * Creates a NetworkError for a connection failure. */ static connectionFailed(message: string, endpoint?: string, cause?: Error): NetworkError; /** * Creates a NetworkError from an HTTP response. */ static fromResponse(statusCode: number, message: string, endpoint?: string): NetworkError; } /** * Authentication error codes for more specific auth error handling. */ export declare enum AuthenticationErrorCode { /** Missing or invalid credentials */ UNAUTHORIZED = "UNAUTHORIZED", /** Valid credentials but insufficient permissions */ FORBIDDEN = "FORBIDDEN", /** Token has expired and needs refresh */ TOKEN_EXPIRED = "TOKEN_EXPIRED" } /** * Error thrown when authentication or authorization fails. * * AuthenticationError covers unauthorized access, forbidden operations, * and token expiration. Most authentication errors are not retryable, * except for TOKEN_EXPIRED which may succeed after token refresh. * * @example * ```typescript * if (!user.isAuthenticated) { * throw new AuthenticationError(AuthenticationErrorCode.UNAUTHORIZED, 'Please log in'); * } * if (!user.hasPermission('admin')) { * throw new AuthenticationError(AuthenticationErrorCode.FORBIDDEN, 'Admin access required'); * } * ``` */ export declare class AuthenticationError extends DB4Error { /** * Specific authentication error code for programmatic handling. */ readonly authErrorCode: AuthenticationErrorCode; /** * The resource or operation that was denied, if available. */ readonly resource?: string; /** * The required permission that was missing, if available. */ readonly requiredPermission?: string; constructor(code: AuthenticationErrorCode, message: string, options?: { resource?: string; requiredPermission?: string; }); /** * Override isRetryable to allow TOKEN_EXPIRED errors to be retried. * Token expiration can be resolved by refreshing the token. */ get isRetryable(): boolean; /** * Override retryGuidance to provide specific guidance for token expiration. */ get retryGuidance(): RetryGuidance; /** * Creates an AuthenticationError for unauthorized access. */ static unauthorized(message: string, resource?: string): AuthenticationError; /** * Creates an AuthenticationError for forbidden operations. */ static forbidden(message: string, options?: { resource?: string; requiredPermission?: string; }): AuthenticationError; /** * Creates an AuthenticationError for expired tokens. */ static tokenExpired(message: string): AuthenticationError; } /** * Result of a single operation in a batch. */ export interface BatchOperationResult { /** Index of the operation in the batch */ index: number; /** Whether the operation succeeded */ success: boolean; /** The result data if successful */ data?: T | undefined; /** The error if failed */ error?: DB4Error | undefined; /** Operation identifier (e.g., document ID) */ operationId?: string | undefined; } /** * Summary statistics for a batch operation. */ export interface BatchSummary { /** Total number of operations in the batch */ total: number; /** Number of successful operations */ succeeded: number; /** Number of failed operations */ failed: number; /** Success rate as a percentage */ successRate: number; /** Errors grouped by error code */ errorsByCode: Record; /** Errors grouped by category */ errorsByCategory: Record; } /** * Aggregate error for batch operations that tracks individual operation results. */ export declare class BatchError extends DB4Error { /** * Results for each operation in the batch. */ readonly results: BatchOperationResult[]; /** * Summary statistics for the batch operation. */ readonly summary: BatchSummary; /** * List of all errors that occurred. */ readonly errors: DB4Error[]; constructor(results: BatchOperationResult[], message?: string); /** * Computes summary statistics from batch results. */ static computeSummary(results: BatchOperationResult[]): BatchSummary; /** * Gets all successful results. */ getSuccessfulResults(): BatchOperationResult[]; /** * Gets all failed results. */ getFailedResults(): BatchOperationResult[]; /** * Gets errors of a specific category. */ getErrorsByCategory(category: ErrorCategory): DB4Error[]; /** * Gets errors of a specific code. */ getErrorsByCode(code: ErrorCode): DB4Error[]; /** * Whether any operations can be retried. */ get hasRetryableErrors(): boolean; /** * Gets indices of operations that can be retried. */ getRetryableIndices(): number[]; /** * Creates a new BatchError with only the retryable operations. */ getRetryableBatch(): BatchOperationResult[]; } /** * Creates a BatchOperationResult for a successful operation. */ export declare function batchSuccess(index: number, data: T, operationId?: string): BatchOperationResult; /** * Creates a BatchOperationResult for a failed operation. */ export declare function batchFailure(index: number, error: DB4Error, operationId?: string): BatchOperationResult; /** * Aggregates results from batch operations into a BatchError or returns null if all succeeded. */ export declare function aggregateBatchResults(results: BatchOperationResult[]): BatchError | null; /** * Check if an error is a DB4Error. */ export declare function isDB4Error(error: unknown): error is DB4Error; /** * Check if an error has a specific error code. */ export declare function hasErrorCode(error: unknown, code: ErrorCode): boolean; /** * Check if an error is in a specific category. */ export declare function hasErrorCategory(error: unknown, category: ErrorCategory): boolean; /** * Check if an error is a conflict error. */ export declare function isConflictError(error: unknown): error is ConflictError; /** * Check if an error is a validation error. */ export declare function isValidationError(error: unknown): error is ValidationError; /** * Check if an error is a document not found error. */ export declare function isDocumentNotFoundError(error: unknown): error is DocumentNotFoundError; /** * Check if an error is a cursor error. */ export declare function isCursorError(error: unknown): error is CursorError; /** * Check if an error is a batch error. */ export declare function isBatchError(error: unknown): error is BatchError; /** * Check if an error is retryable. */ export declare function isRetryableError(error: unknown): boolean; /** * Check if an error is a timeout error (query or transaction). */ export declare function isTimeoutError(error: unknown): boolean; /** * Check if an error is a capacity error. */ export declare function isCapacityError(error: unknown): boolean; /** * Check if an error is a network error. */ export declare function isNetworkError(error: unknown): error is NetworkError; /** * Check if an error is an authentication error. */ export declare function isAuthenticationError(error: unknown): error is AuthenticationError; /** * Wraps an unknown error into a DB4Error. * If the error is already a DB4Error, returns it unchanged. */ export declare function wrapError(error: unknown): DB4Error; /** * Creates an error message from an unknown error. */ export declare function getErrorMessage(error: unknown): string; /** * Creates an error with cause chain support. */ export declare function chainError(code: ErrorCode, message: string, cause: unknown): DB4Error; /** * Calculates the delay for a retry attempt using the error's retry guidance. */ export declare function calculateRetryDelay(error: DB4Error, attempt: number): number; /** * Determines if a retry should be attempted based on the error and attempt number. * The attempt number is 1-based (attempt 1 means we've tried once and are considering retry). */ export declare function shouldRetry(error: DB4Error, attempt: number): boolean; /** * Creates a retry wrapper that executes an operation with automatic retries. */ export declare function withRetry(operation: () => Promise, options?: { maxRetries?: number; onRetry?: (error: DB4Error, attempt: number, delay: number) => void; }): Promise; /** * Interface representing an IceTypeError-like object from @icetype/core. * Used for duck-typing detection since we don't have a direct dependency. */ export interface IceTypeErrorLike extends Error { /** Error code in ICETYPE_xxxx format */ code: string; /** Additional context about the error */ context?: Record; /** Format method for display */ format?: () => string; /** Serialization to JSON */ toJSON?: () => Record; } /** * Interface for ParseError-like objects from @icetype/core. */ export interface ParseErrorLike extends IceTypeErrorLike { /** Line number where the error occurred (1-indexed) */ line?: number; /** Column number where the error occurred (1-indexed) */ column?: number; /** The field or path that caused the error */ path?: string; } /** * Interface for SchemaValidationError-like objects from @icetype/core. */ export interface SchemaValidationErrorLike extends IceTypeErrorLike { /** Path to the invalid field or directive */ path?: string; /** The invalid value that caused the error */ value?: unknown; } /** * Mapping from IceType error code prefixes to DB4 error codes. * * IceType error code ranges: * - ICETYPE_1xxx: Parse errors * - ICETYPE_2xxx: Schema validation errors * - ICETYPE_3xxx: Adapter errors * - ICETYPE_4xxx: Schema loader errors */ export declare const ICETYPE_CODE_TO_DB4_CODE: Record; /** * Retry guidance for IceType error code prefixes. */ export declare const ICETYPE_RETRY_GUIDANCE: Record; /** * Check if an error is an IceTypeError from @icetype/core. * * Uses duck-typing to detect IceTypeError-like objects since we don't have * a direct dependency on @icetype/core. Checks for: * - Error instance with name containing 'IceType' or specific subclass names * - Has a `code` property starting with 'ICETYPE_' * - Has a `format()` method * * @param error - The error to check * @returns True if the error is an IceTypeError * * @example * ```typescript * try { * parseSchema(definition); * } catch (error) { * if (isIceTypeError(error)) { * console.log(`IceType error: ${error.code}`); * // Wrap for unified handling * throw wrapIceTypeError(error); * } * throw error; * } * ``` */ export declare function isIceTypeError(error: unknown): error is IceTypeErrorLike; /** * Maps an IceType error code to a DB4 error code. * * @param iceTypeCode - The IceType error code (e.g., 'ICETYPE_1000') * @returns The corresponding DB4 ErrorCode * * @example * ```typescript * const db4Code = mapIceTypeCodeToErrorCode('ICETYPE_1000'); * // Returns ErrorCode.SCHEMA_VIOLATION * ``` */ export declare function mapIceTypeCodeToErrorCode(iceTypeCode: string): ErrorCode; /** * Gets retry guidance for an IceType error code. * * @param iceTypeCode - The IceType error code (e.g., 'ICETYPE_1000') * @returns Retry guidance for the error, or undefined if not found * * @example * ```typescript * const guidance = getIceTypeRetryGuidance('ICETYPE_3000'); * if (guidance?.retryable) { * // Implement retry logic * } * ``` */ export declare function getIceTypeRetryGuidance(iceTypeCode: string): RetryGuidance | undefined; /** * Wraps an IceTypeError into a DB4Error for unified error handling. * * This function: * - Preserves the original error information in the details * - Maps IceType error codes to DB4 error codes * - Preserves location info from ParseError * - Preserves validation details from SchemaValidationError * - Maintains cause chain * * If the error is already a DB4Error, returns it unchanged. * For non-IceTypeErrors, wraps as INTERNAL_ERROR. * * @param error - The error to wrap * @returns A DB4Error with mapped code and preserved details * * @example * ```typescript * try { * parseSchema(definition); * } catch (error) { * // Unified error handling * const db4Error = wrapIceTypeError(error); * if (db4Error.isRetryable) { * // Retry logic * } * } * ``` */ export declare function wrapIceTypeError(error: unknown): DB4Error; //# sourceMappingURL=errors.d.ts.map