Skip to content

Commit

Permalink
fix: handle decoding error in JSON.parse
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinGong2013 committed Aug 7, 2024
1 parent c7223a5 commit b53638d
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 81 deletions.
14 changes: 13 additions & 1 deletion lib/g_json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ class _JSONNilReason extends Error {
_JSONNilReason.outOfBounds(int index)
: message = 'List($index) Index is out of bounds.';

_JSONNilReason.decode(dynamic error)
: message = 'decode error: ${error.toString()}';

_JSONNilReason(this.message);

@override
Expand Down Expand Up @@ -183,6 +186,11 @@ class JSON {
}

static JSON nil = JSON(null);
static JSON nilWith(Error error) {
final j = JSON.nil;
j.error = error;
return j;
}

/// Convenience method `type == Type.nil`
bool get isNull => _type == Type.nil;
Expand Down Expand Up @@ -320,7 +328,11 @@ class JSON {
if (jsonStr.isEmpty) {
return JSON.nil;
}
return JSON(json.decode(jsonStr));
try {
return JSON(json.decode(jsonStr));
} catch (e) {
return JSON.nilWith(_JSONNilReason.decode(e));
}
}

dynamic _unwrap(object) {
Expand Down
Loading

0 comments on commit b53638d

Please sign in to comment.