@contentstack/cli-utilities
Version:
Utilities for contentstack projects
86 lines (85 loc) • 3.12 kB
TypeScript
import { ClassifiedError, ErrorContext } from '../interfaces';
/**
* Handles errors in a CLI application by classifying, normalizing, and extracting
* relevant information for debugging and logging purposes.
*
* This class provides methods to:
* - Normalize unknown error types into standard `Error` objects.
* - Classify errors into predefined categories such as API errors, network errors,
* server errors, and more.
* - Extract detailed error payloads for logging, including HTTP request and response
* details when applicable.
* - Identify sensitive information in error messages to prevent accidental exposure.
* - Generate debug payloads for enhanced troubleshooting when debugging is enabled.
*
* @remarks
* This class is designed to handle a wide range of error types, including generic
* JavaScript errors, API errors, and custom error objects. It also supports
* optional debugging and context metadata for enhanced error reporting.
*
* @example
* ```typescript
* const errorHandler = new CLIErrorHandler();
*
* try {
* // Some operation that may throw an error
* } catch (error) {
* const classifiedError = errorHandler.classifyError(error, {
* operation: 'fetchData',
* component: 'DataService',
* });
* console.error(classifiedError);
* }
* ```
*
* @public
*/
export default class CLIErrorHandler {
constructor();
/**
* Classifies an error into a structured format for better handling and debugging.
*
* @param error - The error object to classify. Can be of any type.
* @param context - Optional additional context about the error.
* @param errMessage - Optional custom error message to override the default error message.
*
* @returns A `ClassifiedError` object containing essential error details in a clear,
* concise format optimized for debugging.
*/
classifyError(error: unknown, context?: ErrorContext, errMessage?: string): ClassifiedError;
/**
* Extracts a clear, concise error message from various error types.
*/
private extractClearMessage;
/**
* Normalizes various error types into a standard Error object.
*
* @param error - The error to normalize
* @returns A normalized Error object
*/
private normalizeToError;
/**
* Determines the type of error based on its characteristics.
*/
private determineErrorType;
/**
* Extracts only essential error payload information for clear debugging.
*/
private extractErrorPayload;
/**
* Extracts metadata from the error context and adds additional information.
*
* @param context - The error context to extract metadata from
* @param errorType - Optional error type to include in metadata
* @returns An object containing relevant metadata for debugging
*/
private extractMeta;
/**
* Checks if error contains sensitive information.
*
* @param error - Error to check
* @returns True if sensitive info is found
*/
private containsSensitiveInfo;
}
export { CLIErrorHandler };