Skip to content

fix: prevent FormatException crash by wrapping jsonDecode in try-catch#1052

Open
vibhutomer wants to merge 1 commit into
mosip:masterfrom
vibhutomer:fix/json-decode-crash
Open

fix: prevent FormatException crash by wrapping jsonDecode in try-catch#1052
vibhutomer wants to merge 1 commit into
mosip:masterfrom
vibhutomer:fix/json-decode-crash

Conversation

@vibhutomer
Copy link
Copy Markdown

@vibhutomer vibhutomer commented May 13, 2026

Description

This PR resolves a critical vulnerability in NetworkServiceImpl where untrusted network data was parsed without format validation, leading to potential application crashes.

Previously, getVersionNoApp() passed response.body directly into jsonDecode() without a try-catch block. If the server or a proxy returned a malformed payload (such as HTML or an empty string) with a 200 status code, jsonDecode would throw an unhandled FormatException, causing a hard crash.

Changes Made

  • Wrapped the jsonDecode execution in getVersionNoApp() within a try-catch block.
  • Added specific handling for FormatException to log the error and provide a safe fallback value ('Unknown') to ensure the application continues running smoothly even when receiving corrupted payloads.

Related Issue

Closes #1051

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Stability improvement (prevents unhandled exceptions during networking)

Checklist

  • My code follows the style guidelines of this project.
  • I have performed a self-review of my own code.
  • My changes generate no new warnings or exceptions.

Summary by CodeRabbit

  • Bug Fixes
    • Improved stability on Android by enhancing error handling for version information retrieval. The app no longer crashes when version data is unavailable or malformed, instead displaying a fallback value.

Review Change Stack

Signed-off-by: vibhutomer <vibhutomer25@gmail.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

Walkthrough

NetworkServiceImpl.getVersionNoApp() now defensively handles JSON parsing failures by wrapping ActuatorInfo.fromJson(jsonDecode(...)) in a try-catch block. Parsing exceptions log errors and return a safe 'Unknown' fallback instead of crashing the application.

Changes

Network JSON parsing resilience

Layer / File(s) Summary
Version extraction with format exception handling
lib/platform_android/network_service_impl.dart
getVersionNoApp() wraps ActuatorInfo.fromJson(jsonDecode(...)) in try/catch FormatException, logs parsing errors, and returns 'Unknown' as a safe fallback when the network response body is malformed or intercepted with non-JSON content.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A rabbit caught a crash so fast,
From JSON gone astray,
Now wrapped in try, it holds so vast,
'Unknown' saves the day! 🐰✨

🚥 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: wrapping jsonDecode in try-catch to prevent FormatException crashes, which is the core fix in the changeset.
Linked Issues check ✅ Passed The PR successfully addresses all requirements from issue #1051: wraps jsonDecode in try-catch, catches FormatException, logs errors, and returns safe fallback ('Unknown') instead of crashing.
Out of Scope Changes check ✅ Passed All changes are focused on the NetworkServiceImpl.getVersionNoApp() method and directly address the jsonDecode crash issue; 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

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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
Copy Markdown

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/platform_android/network_service_impl.dart`:
- Around line 42-49: The current try block only catches FormatException but
other parsing errors (e.g., TypeError thrown by ActuatorInfo.fromJson) can still
crash; change the catch to a general catch (catch (e, st)) that handles any
thrown object, log the error and stack trace (use debugPrint) and set
versionInfo = 'Unknown' as the safe fallback; reference the
ActuatorInfo.fromJson call and the versionInfo assignment so you update the
existing try { ActuatorInfo.fromJson(...) ... } on FormatException catch (...)
block to use a broad catch and preserve the same fallback behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7e4fc860-8617-493d-baa6-413f7f7a232d

📥 Commits

Reviewing files that changed from the base of the PR and between aef4fb6 and 8cac050.

📒 Files selected for processing (1)
  • lib/platform_android/network_service_impl.dart

Comment on lines +42 to +49
try {
ActuatorInfo actuatorInfo =
ActuatorInfo.fromJson(jsonDecode(response.body));
versionInfo = actuatorInfo.build['version'] ?? 'Unknown';
} on FormatException catch (e) {
debugPrint('Fatal JSON Parsing Error: ${e.message}');
versionInfo = 'Unknown'; // Safe fallback prevents crash
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check ActuatorInfo.fromJson implementation to identify potential exceptions

# Find the ActuatorInfo class definition
ast-grep --pattern $'class ActuatorInfo {
  $$$
}'

# Find the fromJson factory method
ast-grep --pattern $'factory ActuatorInfo.fromJson($$$) {
  $$$
}'

# Check if ActuatorInfo uses code generation (json_serializable)
rg -n "part.*actuator_info.g.dart" lib/model/

# Check the build field declaration
rg -n -A2 "build" lib/model/actuator_info.dart

Repository: mosip/android-registration-client

Length of output: 341


Catch all exceptions to prevent crashes from unexpected JSON structure.

The try-catch only handles FormatException, but ActuatorInfo.fromJson (which uses generated json_serializable code) will throw other exceptions like TypeError if the JSON is valid but structurally unexpected—for example, if the build field is missing or has the wrong type. Catching only FormatException leaves these parsing-related crashes unhandled, which defeats the defensive programming goal.

🛡️ Proposed fix to catch all exceptions
-        } on FormatException catch (e) {
-          debugPrint('Fatal JSON Parsing Error: ${e.message}');
+        } catch (e) {
+          debugPrint('JSON Parsing Error: $e');
           versionInfo = 'Unknown'; // Safe fallback prevents crash
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
ActuatorInfo actuatorInfo =
ActuatorInfo.fromJson(jsonDecode(response.body));
versionInfo = actuatorInfo.build['version'] ?? 'Unknown';
} on FormatException catch (e) {
debugPrint('Fatal JSON Parsing Error: ${e.message}');
versionInfo = 'Unknown'; // Safe fallback prevents crash
}
try {
ActuatorInfo actuatorInfo =
ActuatorInfo.fromJson(jsonDecode(response.body));
versionInfo = actuatorInfo.build['version'] ?? 'Unknown';
} catch (e) {
debugPrint('JSON Parsing Error: $e');
versionInfo = 'Unknown'; // Safe fallback prevents crash
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/platform_android/network_service_impl.dart` around lines 42 - 49, The
current try block only catches FormatException but other parsing errors (e.g.,
TypeError thrown by ActuatorInfo.fromJson) can still crash; change the catch to
a general catch (catch (e, st)) that handles any thrown object, log the error
and stack trace (use debugPrint) and set versionInfo = 'Unknown' as the safe
fallback; reference the ActuatorInfo.fromJson call and the versionInfo
assignment so you update the existing try { ActuatorInfo.fromJson(...) ... } on
FormatException catch (...) block to use a broad catch and preserve the same
fallback behavior.

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.

Unhandled FormatException crash during JSON decoding in NetworkService

1 participant