debug: Add comprehensive logging to trace error handling flow

- Add detailed logging to API key validation function
- Add debug logs to frontend error parsing
- Add debug logs to TanStack Query error handler
- This will help identify where error handling is failing in the UI
This commit is contained in:
leex279
2025-09-12 19:47:47 +02:00
parent 98b798173e
commit 082324b7fc
3 changed files with 58 additions and 24 deletions

View File

@@ -260,6 +260,11 @@ export function useCrawlUrl() {
return response; return response;
}, },
onError: (error, _variables, context) => { onError: (error, _variables, context) => {
console.log(`🔍 [Crawl Hook] Received error:`, error);
console.log(`🔍 [Crawl Hook] Error type: ${typeof error}`);
console.log(`🔍 [Crawl Hook] Error keys:`, Object.keys(error || {}));
console.log(`🔍 [Crawl Hook] Is OpenAI error:`, (error as EnhancedError)?.isOpenAIError);
// Rollback optimistic updates on error // Rollback optimistic updates on error
if (context?.previousKnowledge) { if (context?.previousKnowledge) {
queryClient.setQueryData(knowledgeKeys.lists(), context.previousKnowledge); queryClient.setQueryData(knowledgeKeys.lists(), context.previousKnowledge);
@@ -278,6 +283,8 @@ export function useCrawlUrl() {
const errorMessage = (error as EnhancedError)?.isOpenAIError const errorMessage = (error as EnhancedError)?.isOpenAIError
? getDisplayErrorMessage(error as EnhancedError) ? getDisplayErrorMessage(error as EnhancedError)
: (error instanceof Error ? error.message : "Failed to start crawl"); : (error instanceof Error ? error.message : "Failed to start crawl");
console.log(`🔍 [Crawl Hook] Final error message for toast:`, errorMessage);
showToast(errorMessage, "error"); showToast(errorMessage, "error");
}, },
}); });

View File

@@ -18,6 +18,10 @@ export async function callKnowledgeAPI<T>(
// Use the ETag-aware API client for caching benefits // Use the ETag-aware API client for caching benefits
return await callAPIWithETag<T>(endpoint, options); return await callAPIWithETag<T>(endpoint, options);
} catch (error: any) { } catch (error: any) {
console.log(`🔍 [Knowledge API] Caught error for ${endpoint}:`, error);
console.log(`🔍 [Knowledge API] Error type: ${typeof error}`);
console.log(`🔍 [Knowledge API] Error keys:`, Object.keys(error || {}));
// Apply enhanced error parsing for OpenAI errors // Apply enhanced error parsing for OpenAI errors
const enhancedError = parseKnowledgeBaseError({ const enhancedError = parseKnowledgeBaseError({
status: error.statusCode || error.status, status: error.statusCode || error.status,
@@ -25,12 +29,17 @@ export async function callKnowledgeAPI<T>(
detail: error.detail detail: error.detail
}); });
console.log(`🔍 [Knowledge API] Enhanced error:`, enhancedError);
console.log(`🔍 [Knowledge API] Is OpenAI error:`, enhancedError.isOpenAIError);
console.log(`🔍 [Knowledge API] Error details:`, enhancedError.errorDetails);
// Preserve the original error structure but enhance with our parsing // Preserve the original error structure but enhance with our parsing
const finalError = error as EnhancedError; const finalError = error as EnhancedError;
finalError.isOpenAIError = enhancedError.isOpenAIError; finalError.isOpenAIError = enhancedError.isOpenAIError;
finalError.errorDetails = enhancedError.errorDetails; finalError.errorDetails = enhancedError.errorDetails;
finalError.message = enhancedError.message; finalError.message = enhancedError.message;
console.log(`🔍 [Knowledge API] Final error to throw:`, finalError);
throw finalError; throw finalError;
} }
} }

View File

@@ -100,21 +100,24 @@ async def _validate_openai_api_key() -> None:
Raises: Raises:
HTTPException: 401 if API key is invalid/missing, 429 if quota exhausted HTTPException: 401 if API key is invalid/missing, 429 if quota exhausted
""" """
# Import embedding exceptions for specific error handling
from ..services.embeddings.embedding_exceptions import (
EmbeddingAuthenticationError,
EmbeddingQuotaExhaustedError,
)
try: try:
# Test the API key with a minimal embedding request # Test the API key with a minimal embedding request
from ..services.embeddings.embedding_service import create_embedding from ..services.embeddings.embedding_service import create_embedding
logger.info("🔑 Validating OpenAI API key before starting operation...")
# Try to create a test embedding with minimal content # Try to create a test embedding with minimal content
await create_embedding(text="test") test_result = await create_embedding(text="test")
except Exception as e: if test_result:
# Import embedding exceptions for specific error handling logger.info("✅ OpenAI API key validation successful")
from ..services.embeddings.embedding_exceptions import ( else:
EmbeddingAuthenticationError, logger.error("❌ OpenAI API key validation failed - no embedding returned")
EmbeddingQuotaExhaustedError,
)
if isinstance(e, EmbeddingAuthenticationError):
raise HTTPException( raise HTTPException(
status_code=401, status_code=401,
detail={ detail={
@@ -123,20 +126,35 @@ async def _validate_openai_api_key() -> None:
"error_type": "authentication_failed" "error_type": "authentication_failed"
} }
) )
elif isinstance(e, EmbeddingQuotaExhaustedError):
raise HTTPException( except EmbeddingAuthenticationError as e:
status_code=429, logger.error(f"❌ OpenAI authentication failed: {e}")
detail={ raise HTTPException(
"error": "OpenAI quota exhausted", status_code=401,
"message": "Your OpenAI API key has no remaining credits. Please add credits to your account.", detail={
"error_type": "quota_exhausted" "error": "Invalid OpenAI API key",
} "message": "Please verify your OpenAI API key in Settings before starting a crawl.",
) "error_type": "authentication_failed",
else: "api_key_prefix": getattr(e, "api_key_prefix", None),
# For any other errors, allow the operation to continue }
# The error will be caught later during actual processing ) from None
logger.warning(f"API key validation failed with unexpected error: {e}") except EmbeddingQuotaExhaustedError as e:
pass logger.error(f"❌ OpenAI quota exhausted: {e}")
raise HTTPException(
status_code=429,
detail={
"error": "OpenAI quota exhausted",
"message": "Your OpenAI API key has no remaining credits. Please add credits to your account.",
"error_type": "quota_exhausted",
"tokens_used": getattr(e, "tokens_used", None),
}
) from None
except Exception as e:
# For any other errors, log them but allow the operation to continue
# The error will be caught later during actual processing
logger.warning(f"⚠️ API key validation failed with unexpected error: {e}")
# Don't block the operation for unexpected validation errors
pass
# Request Models # Request Models