Skip to content

Unsafe JSON Decoding->the API returns a 500 error (HTML body) or network error, the app will crash.#154

Open
aniket866 wants to merge 2 commits intoAOSSIE-Org:mainfrom
aniket866:try-catch-block
Open

Unsafe JSON Decoding->the API returns a 500 error (HTML body) or network error, the app will crash.#154
aniket866 wants to merge 2 commits intoAOSSIE-Org:mainfrom
aniket866:try-catch-block

Conversation

@aniket866
Copy link

@aniket866 aniket866 commented Feb 7, 2026

Unsafe JSON Decoding

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling to gracefully manage invalid AI server responses with user-friendly error messages.
    • Enhanced response processing reliability through more robust JSON parsing and data validation.
  • New Features

    • Added support for AI-generated function calls, enabling broader interaction capabilities and response types.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 7, 2026

Warning

Rate limit exceeded

@aniket866 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 20 minutes and 35 seconds before requesting another review.

⌛ 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.

📝 Walkthrough

Walkthrough

The 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

Cohort / File(s) Summary
AI Service Response Handling
lib/services/ai_service.dart
Added try-catch wrapper around JSON response parsing with user-friendly error handling. Implemented function call detection logic to inspect API response candidates and distinguish between function_call type responses (returning function name and arguments) and regular message responses. Adjusted control flow to safely extract response data within guarded path. Updated documentation comment for system message handling.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A hop and a bound, I parse with care,
No crashes when JSON's not there!
Function calls caught mid-flight,
Error handling done just right,
Safe responses—hooray, hooray! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding safe JSON decoding with error handling to prevent app crashes when API returns non-JSON responses.
Linked Issues check ✅ Passed The PR implements all requirements from issue #153: checks response.statusCode before decoding and wraps jsonDecode in try-catch to prevent crashes from non-JSON responses.
Out of Scope Changes check ✅ Passed All changes in AIService.generateChatResponse are directly related to issue #153 requirements; no out-of-scope modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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., missing candidates key, or content without parts), a TypeError is thrown and caught by the outer catch(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 catch from 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: handleToolResponse has the same unguarded jsonDecode pattern this PR aims to fix.

Line 539 calls jsonDecode(response.body) without the try-catch guard that was added to generateChatResponse. The outer catch(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>
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 Decoding->the API returns a 500 error (HTML body) or network error, the app will crash.

1 participant