UNPKG

houser-js-utils

Version:

A comprehensive collection of TypeScript utility functions for common development tasks including array manipulation, string processing, date handling, random number generation, validation, and much more.

507 lines (506 loc) 20.2 kB
/** * Error handling utilities and custom error types for better error management. * * This module provides a comprehensive set of error handling utilities and custom error types * for consistent error management across the application. It includes: * * - Custom error types for different error scenarios * - Error validation utilities * - Error reporting and logging functionality * - Type guards and validation functions * * @module ErrorUtils * @example * ```typescript * // Using custom error types * throw new AuthenticationError("Invalid credentials"); * * // Using validation utilities * ErrorUtils.validateEmail("user@example.com"); * * // Using error handling wrappers * const safeFunction = ErrorUtils.withErrorHandling( * () => riskyOperation(), * (error) => console.error(error) * ); * ``` */ declare global { interface Window { DD_LOGS?: { logger: { error: (message: string, context: Record<string, unknown>) => void; }; }; } } /** * Custom error class for authentication-related errors. * @extends Error */ export declare class AuthenticationError extends Error { constructor(message: string); } /** * Custom error class for authorization-related errors. * @extends Error */ export declare class AuthorizationError extends Error { constructor(message: string); } /** * Custom error class for network-related errors. * @extends Error */ export declare class NetworkError extends Error { constructor(message: string); } /** * Custom error class for resource not found errors. * @extends Error */ export declare class NotFoundError extends Error { constructor(message: string); } /** * Custom error class for timeout-related errors. * @extends Error */ export declare class TimeoutError extends Error { constructor(message: string); } /** * Custom error class for validation-related errors. * @extends Error */ export declare class ValidationError extends Error { constructor(message: string); } /** * Utility object containing error handling and validation functions. */ export declare const ErrorUtils: { /** * Captures and reports an error to DataDog. * * @param error - The error to capture and report * @param options - Options for error capture * @param options.log - Whether to log the error to console (default: true) * @param options.tags - Additional tags to add to the error in DataDog * @param options.context - Additional context to add to the error in DataDog * * @example * ```typescript * try { * // Some risky operation * } catch (error) { * ErrorUtils.captureError(error, { * tags: { component: 'UserService' }, * context: { userId: '123' } * }); * } * ``` */ captureError(error: Error | unknown, options?: { log?: boolean; tags?: Record<string, string>; context?: Record<string, unknown>; }): void; /** * Checks if an error is a specific type of error. * * @param error - The error to check * @param errorType - The type of error to check against * @returns True if the error is of the specified type * * @example * ```typescript * const isAuthError = ErrorUtils.isErrorType(error, AuthenticationError); * ``` */ isErrorType(error: unknown, errorType: new (message: string) => Error): boolean; /** * Validates that a value is a valid array * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid array */ validateArray(value: unknown, message?: string): void; /** * Validates that a value is a valid array length * @param array - Array to validate * @param minLength - Minimum length * @param maxLength - Maximum length * @param message - Error message to throw if validation fails * @throws ValidationError if array length is invalid */ validateArrayLength<T>(array: T[], minLength: number, maxLength: number, message?: string): void; /** * Validates that an array is not empty * @param array - Array to validate * @param message - Error message to throw if validation fails * @throws ValidationError if array is empty */ validateArrayNotEmpty<T>(array: T[], message: string): void; /** * Validates that a value is a valid bigint * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid bigint */ validateBigInt(value: unknown, message?: string): void; /** * Validates that a value is a valid boolean * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid boolean */ validateBoolean(value: unknown, message?: string): void; /** * Validates that a value is a valid credit card number * @param cardNumber - Credit card number to validate * @param message - Error message to throw if validation fails * @throws ValidationError if credit card number is invalid */ validateCreditCard(cardNumber: string, message?: string): void; /** * Validates that a value is a valid date * @param date - Date to validate * @param message - Error message to throw if validation fails * @throws ValidationError if date is invalid */ validateDate(date: string | Date, message?: string): void; /** * Validates that a value is a valid date instance * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid date instance */ validateDateInstance(value: unknown, message?: string): void; /** * Validates that a value is a valid date range * @param startDate - Start date * @param endDate - End date * @param message - Error message to throw if validation fails * @throws ValidationError if date range is invalid */ validateDateRange(startDate: Date | string, endDate: Date | string, message?: string): void; /** * Validates that a value is a valid email address * @param email - Email address to validate * @param message - Error message to throw if validation fails * @throws ValidationError if email is invalid */ validateEmail(email: string, message?: string): void; /** * Validates that a value is a valid enum value * @param value - Value to validate * @param enumObj - Enum object to validate against * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid enum value */ validateEnum<T extends { [key: string]: string | number; }>(value: string | number, enumObj: T, message?: string): void; /** * Validates that a value is a valid file size * @param size - File size in bytes * @param maxSize - Maximum file size in bytes * @param message - Error message to throw if validation fails * @throws ValidationError if file size is invalid */ validateFileSize(size: number, maxSize: number, message?: string): void; /** * Validates that a value is a valid file type * @param file - File to validate * @param allowedTypes - Array of allowed MIME types * @param message - Error message to throw if validation fails * @throws ValidationError if file type is invalid */ validateFileType(file: File, allowedTypes: string[], message?: string): void; /** * Validates that a value is a valid function * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid function */ validateFunction(value: unknown, message?: string): void; /** * Validates that a value is a valid image dimension * @param width - Image width * @param height - Image height * @param maxWidth - Maximum width * @param maxHeight - Maximum height * @param message - Error message to throw if validation fails * @throws ValidationError if image dimension is invalid */ validateImageDimension(width: number, height: number, maxWidth: number, maxHeight: number, message?: string): void; /** * Validates that a value is a valid integer * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid integer */ validateInteger(value: unknown, message?: string): void; /** * Validates that a value is a valid IP address * @param ip - IP address to validate * @param version - IP version (4 or 6) * @param message - Error message to throw if validation fails * @throws ValidationError if IP address is invalid */ validateIP(ip: string, version?: 4 | 6, message?: string): void; /** * Validates that a value is a valid MAC address * @param mac - MAC address to validate * @param message - Error message to throw if validation fails * @throws ValidationError if MAC address is invalid */ validateMAC(mac: string, message?: string): void; /** * Validates that a value is a valid map * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid map */ validateMap(value: unknown, message?: string): void; /** * Validates that a value is a valid negative number * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid negative number */ validateNegativeNumber(value: unknown, message?: string): void; /** * Validates that a value is a valid non-null * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is null */ validateNonNull<T>(value: T | null, message?: string): asserts value is T; /** * Validates that a value is a valid non-null and non-undefined * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is null or undefined */ validateNonNullOrUndefined<T>(value: T | null | undefined, message?: string): asserts value is T; /** * Validates that a value is a valid non-undefined * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is undefined */ validateNonUndefined<T>(value: T | undefined, message?: string): asserts value is T; /** * Validates that a value is a valid null * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not null */ validateNull(value: unknown, message?: string): void; /** * Validates that a value is a valid null or undefined * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not null or undefined */ validateNullOrUndefined(value: unknown, message?: string): void; /** * Validates that a value is not null or undefined * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is null or undefined */ validateNotNull<T>(value: T | null | undefined, message: string): asserts value is T; /** * Validates that a string is not empty * @param value - String to validate * @param message - Error message to throw if validation fails * @throws ValidationError if string is empty */ validateNotEmpty(value: string, message: string): void; /** * Validates that a value is a valid number * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid number */ validateNumber(value: unknown, message?: string): void; /** * Validates that a value is a valid object * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid object */ validateObject(value: unknown, message?: string): void; /** * Validates that a value is a valid object key * @param obj - Object to validate * @param key - Key to validate * @param message - Error message to throw if validation fails * @throws ValidationError if object key is invalid */ validateObjectKey<T extends object>(obj: T, key: keyof T, message?: string): void; /** * Validates that a value is a valid password * @param password - Password to validate * @param options - Password validation options * @throws ValidationError if password doesn't meet requirements */ validatePassword(password: string, options?: { minLength?: number; requireUppercase?: boolean; requireLowercase?: boolean; requireNumber?: boolean; requireSpecialChar?: boolean; message?: string; }): void; /** * Validates that a value is a valid phone number * @param phone - Phone number to validate * @param message - Error message to throw if validation fails * @throws ValidationError if phone number is invalid */ validatePhone(phone: string, message?: string): void; /** * Validates that a value is a valid positive number * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid positive number */ validatePositiveNumber(value: unknown, message?: string): void; /** * Validates that a value is a valid postal code * @param postalCode - Postal code to validate * @param country - Country code for postal code format * @param message - Error message to throw if validation fails * @throws ValidationError if postal code is invalid */ validatePostalCode(postalCode: string, country?: "US" | "CA" | "UK", message?: string): void; /** * Validates that a value is a valid promise * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid promise */ validatePromise(value: unknown, message?: string): void; /** * Validates that a number is within a range * @param value - Number to validate * @param min - Minimum value (inclusive) * @param max - Maximum value (inclusive) * @param message - Error message to throw if validation fails * @throws ValidationError if number is outside range */ validateRange(value: number, min: number, max: number, message: string): void; /** * Validates that a value matches a regular expression * @param value - String to validate * @param regex - Regular expression to match against * @param message - Error message to throw if validation fails * @throws ValidationError if value doesn't match regex */ validateRegex(value: string, regex: RegExp, message: string): void; /** * Validates that a value is a valid regular expression * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid regular expression */ validateRegExp(value: unknown, message?: string): void; /** * Validates that a value is a valid set * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid set */ validateSet(value: unknown, message?: string): void; /** * Validates that a value is a valid social security number * @param ssn - Social security number to validate * @param message - Error message to throw if validation fails * @throws ValidationError if SSN is invalid */ validateSSN(ssn: string, message?: string): void; /** * Validates that a value is a valid string * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid string */ validateString(value: unknown, message?: string): void; /** * Validates that a value is a valid symbol * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid symbol */ validateSymbol(value: unknown, message?: string): void; /** * Validates that a value is a valid time string * @param time - Time string to validate * @param format - Time format (12h or 24h) * @param message - Error message to throw if validation fails * @throws ValidationError if time string is invalid */ validateTime(time: string, format?: "12h" | "24h", message?: string): void; /** * Validates that a value is a valid undefined * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not undefined */ validateUndefined(value: unknown, message?: string): void; /** * Validates that a value is a valid URL * @param url - URL to validate * @param message - Error message to throw if validation fails * @throws ValidationError if URL is invalid */ validateUrl(url: string, message?: string): void; /** * Validates that a value is a valid UUID * @param uuid - UUID to validate * @param version - UUID version (1-5) * @param message - Error message to throw if validation fails * @throws ValidationError if UUID is invalid * @example * ```typescript * // Validate a random UUID (version 4) * ErrorUtils.validateUUID('123e4567-e89b-12d3-a456-426614174000', 4); * * // Validate a time-based UUID (version 1) * ErrorUtils.validateUUID('123e4567-e89b-12d3-a456-426614174000', 1); * ``` */ validateUUID(uuid: string, version?: 1 | 2 | 3 | 4 | 5, message?: string): void; /** * Validates that a value is a valid weak map * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid weak map */ validateWeakMap(value: unknown, message?: string): void; /** * Validates that a value is a valid weak set * @param value - Value to validate * @param message - Error message to throw if validation fails * @throws ValidationError if value is not a valid weak set */ validateWeakSet(value: unknown, message?: string): void; /** * Wraps an async function with error handling * @param fn - Async function to wrap * @param errorHandler - Function to handle errors * @returns Wrapped async function */ withAsyncErrorHandling<T extends (...args: any[]) => Promise<any>>(fn: T, errorHandler: (error: unknown) => void): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>; /** * Wraps a function with error handling * @param fn - Function to wrap * @param errorHandler - Function to handle errors * @returns Wrapped function */ withErrorHandling<T extends (...args: any[]) => any>(fn: T, errorHandler: (error: unknown) => void): (...args: Parameters<T>) => ReturnType<T>; };