gemini-cost-tracker
Version:
CLI tool to display token usage and costs for Gemini and Vertex AI
73 lines • 2.73 kB
JavaScript
import { AppError, ErrorCode } from '../types/index.js';
import { logger } from './logger.js';
import { ERROR_MESSAGES } from './constants.js';
export class ErrorHandler {
static handle(error, context) {
if (error instanceof AppError) {
logger.appError(error.message, error.code, error, context);
return error;
}
if (error instanceof Error) {
const appError = new AppError(ErrorCode.API_ERROR, error.message, {
originalError: error.name,
...context,
});
logger.appError(appError.message, appError.code, error, context);
return appError;
}
const unknownError = new AppError(ErrorCode.API_ERROR, 'An unknown error occurred', {
originalError: String(error),
...context,
});
logger.appError(unknownError.message, unknownError.code, undefined, context);
return unknownError;
}
static createValidationError(message, details) {
return new AppError(ErrorCode.VALIDATION_ERROR, message, details);
}
static createAuthError(message = ERROR_MESSAGES.AUTHENTICATION_FAILED, details) {
return new AppError(ErrorCode.AUTH_ERROR, message, details);
}
static createNetworkError(message = ERROR_MESSAGES.NETWORK_ERROR, details) {
return new AppError(ErrorCode.NETWORK_ERROR, message, details);
}
static createFileError(message = ERROR_MESSAGES.FILE_NOT_FOUND, details) {
return new AppError(ErrorCode.FILE_ERROR, message, details);
}
static createConfigError(message, details) {
return new AppError(ErrorCode.INVALID_CONFIG, message, details);
}
static isNetworkError(error) {
return (error.message.includes('ENOTFOUND') ||
error.message.includes('ECONNREFUSED') ||
error.message.includes('timeout') ||
error.message.includes('Network Error'));
}
static isAuthError(error) {
return (error.message.includes('401') ||
error.message.includes('403') ||
error.message.includes('Unauthorized') ||
error.message.includes('Authentication failed'));
}
}
export function withErrorHandling(fn, context) {
return async (...args) => {
try {
return await fn(...args);
}
catch (error) {
throw ErrorHandler.handle(error, context);
}
};
}
export function withSyncErrorHandling(fn, context) {
return (...args) => {
try {
return fn(...args);
}
catch (error) {
throw ErrorHandler.handle(error, context);
}
};
}
//# sourceMappingURL=errorHandler.js.map