Adds robust error handling for API interactions
Introduces a comprehensive custom error hierarchy for more precise error management in API calls Replaces generic error throwing with specific error types: - Adds custom error classes for various API-related scenarios - Improves error handling in cleanup and API client components - Enables more informative and type-safe error tracking Enhances error reporting and debugging capabilities for Anthropic API interactions
This commit is contained in:
4 files changed
+109
-26
No files matched your search
+22
-13
@@ -3,6 +3,15 @@
|
||||
|
||||
import { requestUrl } from 'obsidian';
|
||||
import { AnthropicRequest, AnthropicResponse, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS, ModelsListResponse } from '../types';
|
||||
import {
|
||||
ApiKeyError,
|
||||
TextTooLongError,
|
||||
ConfigurationError,
|
||||
ServiceUnavailableError,
|
||||
InvalidResponseError,
|
||||
NetworkError,
|
||||
ApiError
|
||||
} from '../errors';
|
||||
|
||||
/**
|
||||
* Client for interacting with the Anthropic Claude API
|
||||
@@ -54,11 +63,11 @@ export class AnthropicClient {
|
||||
customCommentaryPrompt?: string
|
||||
): Promise<{ cleanedText: string; commentary?: string; usage?: { input_tokens: number; output_tokens: number } }> {
|
||||
if (!this.apiKey) {
|
||||
throw new Error('API key is required');
|
||||
throw new ApiKeyError('API key is required');
|
||||
}
|
||||
|
||||
if (text.length > ANTHROPIC_LIMITS.MAX_CHARACTERS) {
|
||||
throw new Error(`Text too long. Maximum ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters allowed.`);
|
||||
throw new TextTooLongError(`Text too long. Maximum ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters allowed.`);
|
||||
}
|
||||
|
||||
// Get commentary prompt if enabled
|
||||
@@ -67,7 +76,7 @@ export class AnthropicClient {
|
||||
if (commentaryStyle === 'custom' && customCommentaryPrompt) {
|
||||
commentaryPrompt = customCommentaryPrompt;
|
||||
} else if (commentaryStyle === 'custom') {
|
||||
throw new Error('Custom commentary style requires a custom prompt. Please provide customCommentaryPrompt.');
|
||||
throw new ConfigurationError('Custom commentary style requires a custom prompt. Please provide customCommentaryPrompt.');
|
||||
} else {
|
||||
commentaryPrompt = COMMENTARY_PRESETS[commentaryStyle as Exclude<CommentaryStyle, 'custom'>];
|
||||
}
|
||||
@@ -204,7 +213,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Failed after ${this.MAX_RETRIES} attempts. Last error: ${lastError.message}`);
|
||||
throw new ServiceUnavailableError(`Failed after ${this.MAX_RETRIES} attempts. Last error: ${lastError.message}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -223,12 +232,12 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
// Extract cleaned text
|
||||
const cleanedTextMatch = responseText.match(/===CLEANED TEXT===([\s\S]*?)===END CLEANED TEXT===/);
|
||||
if (!cleanedTextMatch) {
|
||||
throw new Error('Invalid response format: Could not find cleaned text section');
|
||||
throw new InvalidResponseError('Invalid response format: Could not find cleaned text section');
|
||||
}
|
||||
|
||||
const cleanedText = cleanedTextMatch[1].trim();
|
||||
if (!cleanedText) {
|
||||
throw new Error('Empty cleaned text received');
|
||||
throw new InvalidResponseError('Empty cleaned text received');
|
||||
}
|
||||
|
||||
let commentary: string | undefined;
|
||||
@@ -255,7 +264,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
*/
|
||||
async fetchModels(): Promise<ModelsListResponse> {
|
||||
if (!this.apiKey) {
|
||||
throw new Error('API key is required');
|
||||
throw new ApiKeyError('API key is required');
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -269,7 +278,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
});
|
||||
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw new Error(`Models API request failed: ${response.status}\n${response.text}`);
|
||||
throw new ApiError(`Models API request failed: ${response.status}\n${response.text}`, response.status, response.text);
|
||||
}
|
||||
|
||||
return response.json as ModelsListResponse;
|
||||
@@ -277,7 +286,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
if (error instanceof Error) {
|
||||
throw error;
|
||||
}
|
||||
throw new Error(`Network request failed: ${String(error)}`);
|
||||
throw new NetworkError(`Network request failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,7 +315,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
const errorBody = response.text || 'Unknown error';
|
||||
throw new Error(`API request failed (${response.status}): ${errorBody}`);
|
||||
throw new ApiError(`API request failed (${response.status}): ${errorBody}`, response.status, errorBody);
|
||||
}
|
||||
|
||||
return response.json as AnthropicResponse;
|
||||
@@ -314,7 +323,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
if (error instanceof Error) {
|
||||
throw error;
|
||||
}
|
||||
throw new Error(`Network request failed: ${String(error)}`);
|
||||
throw new NetworkError(`Network request failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,12 +339,12 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
*/
|
||||
private extractTextFromResponse(response: AnthropicResponse): string {
|
||||
if (!response.content || response.content.length === 0) {
|
||||
throw new Error('No content received from API');
|
||||
throw new InvalidResponseError('No content received from API');
|
||||
}
|
||||
|
||||
const text = response.content[0].text;
|
||||
if (!text || text.trim().length === 0) {
|
||||
throw new Error('Empty response from API');
|
||||
throw new InvalidResponseError('Empty response from API');
|
||||
}
|
||||
|
||||
return text.trim();
|
||||
|
||||
+10
-11
@@ -4,6 +4,7 @@
|
||||
import { Editor, MarkdownView, Notice } from 'obsidian';
|
||||
import { CleanupService } from '../services/cleanupService';
|
||||
import { FreewritingCleanupSettings, ANTHROPIC_LIMITS } from '../types';
|
||||
import { ApiKeyError, TextTooLongError, ServiceUnavailableError } from '../errors';
|
||||
|
||||
/**
|
||||
* Command handler for freewriting cleanup operations
|
||||
@@ -72,17 +73,15 @@ export class CleanupCommand {
|
||||
editor.setCursor(insertPosition);
|
||||
editor.replaceRange(formattedResult, insertPosition);
|
||||
} catch (error) {
|
||||
// Handle specific error types
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('API key')) {
|
||||
new Notice('API key error. Please check your settings.');
|
||||
} else if (error.message.includes('too long')) {
|
||||
new Notice('Text is too long for processing.');
|
||||
} else if (error.message.includes('Failed after')) {
|
||||
new Notice('Service temporarily unavailable. Please try again.');
|
||||
} else {
|
||||
new Notice(`Cleanup failed: ${error.message}`);
|
||||
}
|
||||
// Handle specific error types using instanceof checks
|
||||
if (error instanceof ApiKeyError) {
|
||||
new Notice('API key error. Please check your settings.');
|
||||
} else if (error instanceof TextTooLongError) {
|
||||
new Notice('Text is too long for processing.');
|
||||
} else if (error instanceof ServiceUnavailableError) {
|
||||
new Notice('Service temporarily unavailable. Please try again.');
|
||||
} else if (error instanceof Error) {
|
||||
new Notice(`Cleanup failed: ${error.message}`);
|
||||
} else {
|
||||
new Notice('An unexpected error occurred during cleanup.');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// ABOUTME: Custom error types for more robust error handling
|
||||
// ABOUTME: Provides type-safe error categorization instead of fragile string matching
|
||||
|
||||
/**
|
||||
* Base error class for plugin-specific errors
|
||||
*
|
||||
* Provides common foundation for all custom error types in the plugin.
|
||||
* Ensures proper error name is set for instanceof checks and debugging.
|
||||
*/
|
||||
export class PluginError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
// Maintains proper prototype chain for instanceof checks
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when API key is missing or invalid
|
||||
*
|
||||
* Indicates user needs to configure their Anthropic API key in settings.
|
||||
*/
|
||||
export class ApiKeyError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when text exceeds API character or token limits
|
||||
*
|
||||
* Indicates selected text is too large to process with current API limits.
|
||||
*/
|
||||
export class TextTooLongError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when retry attempts are exhausted
|
||||
*
|
||||
* Indicates the service is temporarily unavailable after multiple retry attempts.
|
||||
*/
|
||||
export class ServiceUnavailableError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when API response format is invalid or empty
|
||||
*
|
||||
* Indicates unexpected response structure from the API that cannot be parsed.
|
||||
*/
|
||||
export class InvalidResponseError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when required configuration is missing
|
||||
*
|
||||
* Indicates user needs to provide additional configuration (e.g., custom prompt).
|
||||
*/
|
||||
export class ConfigurationError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when network request fails
|
||||
*
|
||||
* Indicates connectivity issues or network-level failures.
|
||||
*/
|
||||
export class NetworkError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when API returns an error status
|
||||
*
|
||||
* Wraps API error responses with status codes and error details.
|
||||
*/
|
||||
export class ApiError extends PluginError {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status?: number,
|
||||
public readonly responseBody?: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
import { Notice } from 'obsidian';
|
||||
import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
||||
import { ApiKeyError, TextTooLongError } from '../errors';
|
||||
|
||||
/**
|
||||
* Service for orchestrating text cleanup operations
|
||||
@@ -53,12 +54,12 @@ export class CleanupService {
|
||||
}
|
||||
|
||||
if (!this.client.validateApiKey()) {
|
||||
throw new Error('API key is not configured. Please check your plugin settings.');
|
||||
throw new ApiKeyError('API key is not configured. Please check your plugin settings.');
|
||||
}
|
||||
|
||||
// Check text length limits
|
||||
if (text.length > ANTHROPIC_LIMITS.MAX_CHARACTERS) {
|
||||
throw new Error(`Selected text is too long (${text.length} characters). Maximum allowed: ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters.`);
|
||||
throw new TextTooLongError(`Selected text is too long (${text.length} characters). Maximum allowed: ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters.`);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
Reference in new issue
Block a user