UNPKG

@zhanghongping/json-sage-workflow-cli

Version:

An intelligent JSON processing workflow system with improved error handling and configuration

102 lines (101 loc) 3.32 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.JsonSageError = exports.RetryableError = exports.ApiError = void 0; exports.safeJsonParse = safeJsonParse; exports.safeExecute = safeExecute; exports.retryWithBackoff = retryWithBackoff; exports.handleApiError = handleApiError; const chalk_1 = __importDefault(require("chalk")); class ApiError extends Error { constructor(statusCode, message) { super(message); this.statusCode = statusCode; this.name = 'ApiError'; } } exports.ApiError = ApiError; class RetryableError extends Error { constructor(message) { super(message); this.name = 'RetryableError'; } } exports.RetryableError = RetryableError; class JsonSageError extends Error { constructor(message, code, details) { super(message); this.code = code; this.details = details; this.name = 'JsonSageError'; } } exports.JsonSageError = JsonSageError; function safeJsonParse(data) { try { const parsed = JSON.parse(data); return { success: true, data: parsed }; } catch (error) { return { success: false, error: new JsonSageError('Error parsing JSON data. Please ensure the input is valid JSON.', 'INVALID_JSON', error) }; } } async function safeExecute(fn, errorMessage = 'An unexpected error occurred') { try { const result = await fn(); return { success: true, data: result }; } catch (error) { return { success: false, error: new JsonSageError(errorMessage, 'EXECUTION_ERROR', error) }; } } async function retryWithBackoff(operation, options = {}) { const { maxRetries = 3, initialDelay = 1000, maxDelay = 10000, shouldRetry = (error) => { if (error instanceof ApiError) { return [502, 503, 504].includes(error.statusCode); } return error instanceof RetryableError; } } = options; let lastError; let delay = initialDelay; for (let attempt = 1; attempt <= maxRetries; attempt++) { try { return await operation(); } catch (error) { lastError = error; if (!shouldRetry(error) || attempt === maxRetries) { break; } console.log(chalk_1.default.yellow(`Attempt ${attempt} failed, retrying in ${delay}ms...`)); await new Promise(resolve => setTimeout(resolve, delay)); delay = Math.min(delay * 2, maxDelay); } } throw lastError; } function handleApiError(error) { if (error instanceof ApiError) { throw new Error(`API Error (${error.statusCode}): ${error.message}`); } else if (error instanceof RetryableError) { throw new Error(`Retryable Error: ${error.message}`); } else if (error instanceof JsonSageError) { throw new Error(`JSON Sage Error (${error.code}): ${error.message}`); } else if (error instanceof Error) { throw new Error(`Unexpected Error: ${error.message}`); } else { throw new Error('An unknown error occurred'); } }