/** * Base error class for all application errors */ export class BaseError extends Error { constructor( message: string, public readonly code: string = 'UNKNOWN_ERROR', public readonly cause?: unknown ) { super(message); this.name = this.constructor.name; // Capture stack trace Error.captureStackTrace(this, this.constructor); } /** * Convert error to a plain object for logging */ toJSON(): Record { return { name: this.name, message: this.message, code: this.code, stack: this.stack, cause: this.cause instanceof Error ? { name: this.cause.name, message: this.cause.message, stack: this.cause.stack } : this.cause }; } } /** * Error class for AWS service errors */ export class AwsServiceError extends BaseError { constructor( message: string, code: string = 'AWS_SERVICE_ERROR', cause?: unknown ) { super(message, code, cause); } } /** * Error class for MCP client errors */ export class ClientError extends BaseError { constructor( message: string, code: string = 'CLIENT_ERROR', cause?: unknown ) { super(message, code, cause); } } /** * Error class for configuration errors */ export class ConfigError extends BaseError { constructor( message: string, code: string = 'CONFIG_ERROR', cause?: unknown ) { super(message, code, cause); } } /** * Helper function to parse and enhance errors * @param error Original error * @param defaultMessage Default message to use if error is not an Error instance * @returns Formatted error message */ export function formatError(error: unknown, defaultMessage = 'An unknown error occurred'): string { if (error instanceof Error) { return `${error.name}: ${error.message}`; } if (typeof error === 'string') { return error; } return defaultMessage; } /** * Convert any error to a BaseError * @param error Original error * @param defaultMessage Default message to use if error is not an Error instance * @returns BaseError instance */ export function toBaseError(error: unknown, defaultMessage = 'An unknown error occurred'): BaseError { if (error instanceof BaseError) { return error; } if (error instanceof Error) { return new BaseError(error.message, 'WRAPPED_ERROR', error); } return new BaseError( typeof error === 'string' ? error : defaultMessage, 'UNKNOWN_ERROR', error ); }