fix: prevent FormatException crash by wrapping jsonDecode in try-catch#1052
fix: prevent FormatException crash by wrapping jsonDecode in try-catch#1052vibhutomer wants to merge 1 commit into
Conversation
Signed-off-by: vibhutomer <vibhutomer25@gmail.com>
Walkthrough
ChangesNetwork JSON parsing resilience
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)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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
🤖 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
📒 Files selected for processing (1)
lib/platform_android/network_service_impl.dart
| 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 | ||
| } |
There was a problem hiding this comment.
🧩 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.dartRepository: 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.
| 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.
Description
This PR resolves a critical vulnerability in
NetworkServiceImplwhere untrusted network data was parsed without format validation, leading to potential application crashes.Previously,
getVersionNoApp()passedresponse.bodydirectly intojsonDecode()without atry-catchblock. If the server or a proxy returned a malformed payload (such as HTML or an empty string) with a 200 status code,jsonDecodewould throw an unhandledFormatException, causing a hard crash.Changes Made
jsonDecodeexecution ingetVersionNoApp()within atry-catchblock.FormatExceptionto 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
Checklist
Summary by CodeRabbit