fix: improve server action resilience and error logging

- Moved Supabase client initialization inside try-catch in Server Actions
- Added safety checks for null Supabase client in magicScan
- Added detailed server-side logging for debugging deployment issues
- Ensures all failure paths return a structured error response instead of 500
This commit is contained in:
2025-12-19 14:28:40 +01:00
parent cbb28b389c
commit e2c9bef8f4
4 changed files with 77 additions and 34 deletions

View File

@@ -9,13 +9,16 @@ import { trackApiUsage } from './track-api-usage';
import { checkCreditBalance, deductCredits } from './credit-service';
export async function analyzeBottle(base64Image: string, tags?: string[], locale: string = 'de'): Promise<AnalysisResponse> {
const supabase = createServerActionClient({ cookies });
if (!process.env.GEMINI_API_KEY) {
return { success: false, error: 'GEMINI_API_KEY is not configured.' };
}
let supabase; // Declare supabase outside try block for error tracking access
try {
// Initialize Supabase client inside the try block
supabase = createServerActionClient({ cookies });
console.log('[analyzeBottle] Initialized Supabase client');
// ... (auth and credit check remain same) ...
const { data: { session } } = await supabase.auth.getSession();
if (!session || !session.user) {
@@ -110,15 +113,17 @@ export async function analyzeBottle(base64Image: string, tags?: string[], locale
// Track failed API call
try {
const { data: { session } } = await supabase.auth.getSession();
if (session?.user) {
await trackApiUsage({
userId: session.user.id,
apiType: 'gemini_ai',
endpoint: 'generateContent',
success: false,
errorMessage: error instanceof Error ? error.message : 'Unknown error'
});
if (supabase) {
const { data: { session } } = await supabase.auth.getSession();
if (session?.user) {
await trackApiUsage({
userId: session.user.id,
apiType: 'gemini_ai',
endpoint: 'generateContent',
success: false,
errorMessage: error instanceof Error ? error.message : 'Unknown error'
});
}
}
} catch (trackError) {
console.error('Failed to track error:', trackError);