Skip to content

Commit 8524a02

Browse files
committed
refactor: eliminate nested try-catch complexity in pricing fetcher
- Extract fallback logic into handleFallbackToCachedPricing() method - Simplify ensurePricingLoaded() by removing nested try-catch structure - Improve code readability and maintainability - Addresses Copilot review suggestion about nested try-catch complexity
1 parent 8a9dc1a commit 8524a02

1 file changed

Lines changed: 23 additions & 16 deletions

File tree

‎src/pricing-fetcher.ts‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,28 @@ export class PricingFetcher implements Disposable {
5454
return pricing;
5555
}
5656

57+
/**
58+
* Handles fallback to offline pricing when network fetch fails
59+
* @param originalError - The original error from the network fetch
60+
* @returns Map of model names to pricing information
61+
* @throws Error if both network fetch and fallback fail
62+
*/
63+
private async handleFallbackToCachedPricing(originalError: unknown): Promise<Map<string, ModelPricing>> {
64+
logger.warn('Failed to fetch model pricing from LiteLLM, falling back to cached pricing data');
65+
logger.debug('Fetch error details:', originalError);
66+
67+
try {
68+
const fallbackPricing = await this.loadOfflinePricing();
69+
logger.info(`Using cached pricing data for ${fallbackPricing.size} models`);
70+
return fallbackPricing;
71+
}
72+
catch (fallbackError) {
73+
logger.error('Failed to load cached pricing data as fallback:', fallbackError);
74+
logger.error('Original fetch error:', originalError);
75+
throw new Error('Could not fetch model pricing data and fallback data is unavailable');
76+
}
77+
}
78+
5779
/**
5880
* Ensures pricing data is loaded, either from cache or by fetching
5981
* Automatically falls back to offline mode if network fetch fails
@@ -96,22 +118,7 @@ export class PricingFetcher implements Disposable {
96118
return pricing;
97119
}
98120
catch (error) {
99-
// Fallback to offline mode when network fetch fails
100-
logger.warn('Failed to fetch model pricing from LiteLLM, falling back to cached pricing data');
101-
logger.debug('Fetch error details:', error);
102-
103-
try {
104-
// Attempt to use pre-fetched pricing data as fallback
105-
const fallbackPricing = await this.loadOfflinePricing();
106-
logger.info(`Using cached pricing data for ${fallbackPricing.size} models`);
107-
return fallbackPricing;
108-
}
109-
catch (fallbackError) {
110-
// If even the fallback fails, log both errors and throw
111-
logger.error('Failed to load cached pricing data as fallback:', fallbackError);
112-
logger.error('Original fetch error:', error);
113-
throw new Error('Could not fetch model pricing data and fallback data is unavailable');
114-
}
121+
return this.handleFallbackToCachedPricing(error);
115122
}
116123
}
117124

0 commit comments

Comments
 (0)