Skip to content

fix: safe JSON parsing in generateChatResponse#253

Open
Priyanshu-byte-coder wants to merge 1 commit into
AOSSIE-Org:mainfrom
Priyanshu-byte-coder:fix/safe-json-parsing-gemini-response
Open

fix: safe JSON parsing in generateChatResponse#253
Priyanshu-byte-coder wants to merge 1 commit into
AOSSIE-Org:mainfrom
Priyanshu-byte-coder:fix/safe-json-parsing-gemini-response

Conversation

@Priyanshu-byte-coder

Copy link
Copy Markdown

Summary

Closes #170

generateChatResponse() used unchecked casts (as List<dynamic>) and deep indexing (candidates[0]['content']['parts'][0]['text']) on Gemini API responses. Any deviation from the expected structure (rate limit, 500 error returning HTML, empty candidates, missing fields) would cause TypeError, RangeError, or NoSuchMethodError crashes.

Changes

lib/services/ai_service.dart — both the main chat block and the function-execution block:

  1. jsonDecode wrapped in try/catch — returns controlled error if body isn't valid JSON
  2. candidatesRaw is! List || isEmpty guard before indexing
  3. contentRaw is! Map guard before accessing ['parts']
  4. partsRaw is! List guard before iterating
  5. part is Map check before containsKey('functionCall')
  6. Null-safe text extraction via ?.toString() ?? ''

Before / After

// Before — crashes on malformed response
final candidates = responseData['candidates'] as List<dynamic>; // ❌ unsafe cast
return candidates[0]['content']['parts'][0]['text'] ?? '';       // ❌ unsafe indexing

// After — safe
final candidatesRaw = responseData['candidates'];
if (candidatesRaw is! List || candidatesRaw.isEmpty) {
  return {'type': 'error', 'content': 'No response generated'};
}

@coderabbitai

coderabbitai Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@Priyanshu-byte-coder has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 56 minutes and 15 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: fb2b6bd9-4690-46c4-88d1-e10c815ae7a9

📥 Commits

Reviewing files that changed from the base of the PR and between 1cea2a6 and 4fb9f34.

📒 Files selected for processing (1)
  • lib/services/ai_service.dart
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: Unsafe JSON parsing in generateChatResponse() may cause runtime crashes on malformed Gemini responses

1 participant