Error Handling Guide
Complete Processing Flow
Comprehensive error detection flowchart
Detection Flowchart
graph TD
A[API Response] --> B{candidatesTokenCount?}
B -->|= 0| C[Content Review Rejected]
B -->|> 0| D{Check candidates}
D -->|null/empty| E[System Error]
D -->|exists| F{finishReason?}
F -->|!= STOP| G[Generation Rejected]
F -->|= STOP| H{Check parts}
H -->|empty| I[No Data Error]
H -->|exists| J{Has image?}
J -->|Yes| K[Success]
J -->|No| L{Has text?}
L -->|Yes| M[Text Response Error]
L -->|No| N[Unknown Error]Processing Steps
Step 1: Check candidatesTokenCount
if (data.usageMetadata?.candidatesTokenCount === 0) {
return {
errorType: 'ZERO_CANDIDATES_TOKEN',
userMessage: 'Content review failed'
};
}Step 2: Check candidates
if (!data.candidates || !data.candidates.length) {
return {
errorType: 'NO_CANDIDATES',
userMessage: 'System error, please retry'
};
}Step 3: Check finishReason
const candidate = data.candidates[0];
if (candidate.finishReason && candidate.finishReason !== 'STOP') {
return {
errorType: 'FINISH_REASON',
finishReason: candidate.finishReason
};
}Step 4: Extract content
const parts = candidate.content.parts;
const images = parts.filter(p => p.inlineData?.data);
const texts = parts.filter(p => p.text);
if (images.length > 0) {
return { success: true, images };
}
if (texts.length > 0) {
return { errorType: 'TEXT_RESPONSE', text: texts[0].text };
}
return { errorType: 'UNKNOWN' };Error Priority
- Highest:
candidatesTokenCount = 0 - High:
finishReason != STOP - Medium: Text response
- Low: Other technical errors
Related Docs
How is this guide?