UNPKG

@letsparky/api-v2-client

Version:

TypeScript client for the LetsParky API V2

262 lines (261 loc) 8.08 kB
/** * Context information for API errors. * * This interface provides additional context about when and where an error occurred, * which is useful for debugging and error tracking. * * @since 1.0.0 */ export interface ErrorContext { /** HTTP method used for the request (e.g., 'GET', 'POST') */ method?: string; /** URL that was being accessed when the error occurred */ url?: string; /** Unique request identifier for tracking */ requestId?: string; /** Timestamp when the error occurred (Unix timestamp in milliseconds) */ timestamp?: number; /** User agent string of the client */ userAgent?: string; } /** * Base API error class for all LetsParky API errors. * * This class extends the standard Error class with additional properties * specific to API errors, including HTTP status codes, error codes, * and contextual information. * * @example * ```typescript * try { * await client.get('/devices/invalid-id'); * } catch (error) { * if (error instanceof ApiError) { * console.log(`Error ${error.code}: ${error.message}`); * console.log(`HTTP Status: ${error.status}`); * * if (error.isNotFoundError()) { * console.log('Resource not found'); * } else if (error.isAuthError()) { * console.log('Authentication required'); * } * } * } * ``` * * @since 1.0.0 */ export declare class ApiError extends Error { /** Error code identifying the type of error */ readonly code: string; /** HTTP status code associated with the error */ readonly status: number; /** Additional error data from the API response */ readonly data?: any; /** Context information about when/where the error occurred */ readonly context?: ErrorContext; /** * Creates a new ApiError instance. * * @param message - Human-readable error message * @param code - Error code identifying the error type * @param status - HTTP status code * @param data - Additional error data from the API * @param context - Context information about the error * * @since 1.0.0 */ constructor(message: string, code: string, status: number, data?: any, context?: ErrorContext); /** * Check if this error is related to authentication */ isAuthError(): boolean; /** * Check if this error is related to permissions */ isPermissionError(): boolean; /** * Check if this error is due to a resource not being found */ isNotFoundError(): boolean; /** * Check if this error is related to rate limiting */ isRateLimitError(): boolean; /** * Check if this error is due to server issues */ isServerError(): boolean; /** * Check if this error is due to client issues (4xx errors) */ isClientError(): boolean; /** * Get a formatted error message with context */ getFormattedMessage(): string; /** * Convert error to a plain object for serialization */ toJSON(): Record<string, any>; } /** * Error thrown when network-related issues occur. * * This error is thrown when the request fails due to network connectivity * issues, timeouts, or other network-related problems. * * @example * ```typescript * try { * await client.get('/devices'); * } catch (error) { * if (error instanceof NetworkError) { * console.log('Network connectivity issue'); * // Retry logic or offline handling * } * } * ``` * * @since 1.0.0 */ export declare class NetworkError extends ApiError { /** * Creates a new NetworkError instance. * * @param message - Error message (default: 'Network error occurred') * @param context - Context information about the error * * @since 1.0.0 */ constructor(message?: string, context?: ErrorContext); } /** * Error thrown when authentication fails or is required. * * This error is thrown when the API request requires authentication * but no valid credentials are provided, or when the provided * credentials are invalid. * * @example * ```typescript * try { * await client.get('/devices'); * } catch (error) { * if (error instanceof AuthenticationError) { * console.log('Authentication required'); * // Redirect to login or refresh token * } * } * ``` * * @since 1.0.0 */ export declare class AuthenticationError extends ApiError { /** * Creates a new AuthenticationError instance. * * @param message - Error message (default: 'Authentication failed') * @param context - Context information about the error * * @since 1.0.0 */ constructor(message?: string, context?: ErrorContext); } /** * Error thrown when input validation fails. * * This error is thrown when the provided parameters fail validation * before being sent to the API. It includes detailed field-specific * error information to help identify what needs to be corrected. * * @example * ```typescript * try { * await devices.create({ name: '', type: 'invalid' }); * } catch (error) { * if (error instanceof ValidationError) { * console.log('Validation errors:'); * Object.entries(error.errors).forEach(([field, messages]) => { * console.log(` ${field}: ${messages.join(', ')}`); * }); * * // Check specific field errors * if (error.hasFieldError('name')) { * console.log('Name field has errors:', error.getFieldErrors('name')); * } * } * } * ``` * * @since 1.0.0 */ export declare class ValidationError extends ApiError { /** Field-specific validation errors */ readonly errors: Record<string, string[]>; /** * Creates a new ValidationError instance. * * @param message - General error message * @param errors - Field-specific validation errors * @param context - Context information about the error * * @since 1.0.0 */ constructor(message: string, errors?: Record<string, string[]>, context?: ErrorContext); /** * Get all validation errors as a flat array of messages */ getAllErrors(): string[]; /** * Check if a specific field has validation errors */ hasFieldError(field: string): boolean; /** * Get validation errors for a specific field */ getFieldErrors(field: string): string[]; } export declare class TokenExpiredError extends ApiError { constructor(message?: string, context?: ErrorContext); } export declare class RateLimitError extends ApiError { readonly retryAfter: number; constructor(message?: string, retryAfter?: number, context?: ErrorContext); } export declare class ConfigurationError extends Error { readonly code: string; constructor(message: string, code?: string); } /** * Create a standardized error from an unknown error object */ export declare function createStandardError(error: any, defaultMessage?: string, context?: ErrorContext): ApiError; /** * Error codes enum for consistent error handling */ export declare enum ErrorCodes { AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED", TOKEN_EXPIRED = "TOKEN_EXPIRED", INVALID_CREDENTIALS = "INVALID_CREDENTIALS", UNAUTHORIZED = "UNAUTHORIZED", FORBIDDEN = "FORBIDDEN", INSUFFICIENT_PERMISSIONS = "INSUFFICIENT_PERMISSIONS", VALIDATION_ERROR = "VALIDATION_ERROR", INVALID_INPUT = "INVALID_INPUT", MISSING_REQUIRED_FIELD = "MISSING_REQUIRED_FIELD", NOT_FOUND = "NOT_FOUND", RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND", RESOURCE_ALREADY_EXISTS = "RESOURCE_ALREADY_EXISTS", RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED", TOO_MANY_REQUESTS = "TOO_MANY_REQUESTS", NETWORK_ERROR = "NETWORK_ERROR", TIMEOUT_ERROR = "TIMEOUT_ERROR", CONNECTION_ERROR = "CONNECTION_ERROR", INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR", SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE", CONFIGURATION_ERROR = "CONFIGURATION_ERROR", INVALID_ENVIRONMENT = "INVALID_ENVIRONMENT", UNKNOWN_ERROR = "UNKNOWN_ERROR", HTTP_ERROR = "HTTP_ERROR" }