Unsafe JSON Decoding->the API returns a 500 error (HTML body) or network error, the app will crash.#154
Unsafe JSON Decoding->the API returns a 500 error (HTML body) or network error, the app will crash.#154aniket866 wants to merge 2 commits intoAOSSIE-Org:mainfrom
Conversation
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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. 📝 WalkthroughWalkthroughThe change adds safe JSON parsing with try-catch error handling to prevent crashes when the API returns invalid responses, and extends the AI service to detect and return function calls from API responses alongside regular messages. Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@lib/services/ai_service.dart`:
- Around line 416-421: The return branch re-traverses
candidates[0]['content']['parts'][0]['text'] instead of using the
already-extracted content/parts variables; update the 'message' return to use
the in-scope parts variable (e.g., parts[0]['text'] ?? '') to avoid redundant
access and reduce null-dereference risk in the surrounding function that handles
candidates/content/parts.
🧹 Nitpick comments (2)
lib/services/ai_service.dart (2)
396-421: Null-unsafe access on response structure may mask valid API responses as "invalid response".Lines 397, 399–400 cast values directly (
as List<dynamic>) without null checks. If the API returns valid JSON but with an unexpected structure (e.g., missingcandidateskey, orcontentwithoutparts), aTypeErroris thrown and caught by the outercatch(e), which reports "invalid response from the AI server" — misleading for what is actually a structural issue, not a JSON parse failure.Consider adding null checks before casting, or separate the JSON parse
catchfrom the response-traversal logic:Suggested improvement
try { final responseData = jsonDecode(response.body); - final candidates = responseData['candidates'] as List<dynamic>; - if (candidates.isNotEmpty) { - final content = candidates[0]['content']; - final parts = content['parts'] as List<dynamic>; + final candidates = responseData['candidates'] as List<dynamic>?; + if (candidates != null && candidates.isNotEmpty) { + final content = candidates[0]['content'] as Map<String, dynamic>?; + final parts = content?['parts'] as List<dynamic>?; + if (parts == null || parts.isEmpty) { + return { + 'type': 'error', + 'content': 'No response generated', + }; + } for (var part in parts) { - if (part.containsKey('functionCall')) { + if (part is Map<String, dynamic> && part.containsKey('functionCall')) {
538-539:handleToolResponsehas the same unguardedjsonDecodepattern this PR aims to fix.Line 539 calls
jsonDecode(response.body)without the try-catch guard that was added togenerateChatResponse. The outercatch(e)on line 549 prevents a crash, but it silently returns'Function executed successfully.'on parse failure — which is misleading. Consider applying the same defensive pattern here for consistency.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Unsafe JSON Decoding
Where:
AIService.generateChatResponseIssue: jsonDecode(response.body) is called without a try-catch block. If the API returns a 500 error (HTML body) or network error, the app will crash.
Fix: Check response.statusCode before decoding and use try-catch.
why?If the API returns a 500 error (HTML body) or network error, the app will crash.
@SharkyBytes Closes BUG:Unsafe JSON Decoding->the API returns a 500 error (HTML body) or network error, the app will crash. #153
Summary by CodeRabbit
Bug Fixes
New Features