JSON
JSON copied to clipboard
JSON error handling improvement
Hi!
use JSON;
my $foo = JSON::from_json('{blah}');
$ perl /tmp/a.pl
'"' expected, at character offset 1 (before "blah}") at JSON.pm line 198.
This makes it look like there's an error in JSON.pm, due to a die()
Or
use JSON;
my $foo = JSON::to_json(\*STDERR);
$ perl /tmp/a.pl
cannot encode reference to scalar 'GLOB(0x558052844fd0)' unless the scalar is 0 or 1 at JSON.pm line 176.
Attached patch to kick errors back to the caller, referencing the caller stack location instead
diff --git a/lib/JSON.pm b/lib/JSON.pm
index 3e644cc..39d7b1f 100644
--- a/lib/JSON.pm
+++ b/lib/JSON.pm
@@ -170,7 +170,12 @@ sub to_json ($@) {
}
}
- $json->encode($_[0]);
+ my $result;
+ eval { $result = $json->encode($_[0]); };
+
+ Carp::croak "to_json: " . $@ if ($@);
+
+ return $result;
}
@@ -187,7 +192,12 @@ sub from_json ($@) {
}
}
- return $json->decode( $_[0] );
+ my $result;
+ eval { $result = $json->decode( $_[0] ) };
+
+ Carp::croak "from_json: " . $@ if ($@);
+
+ return $result;
}
Now we have a nice error:
$ perl test_json.pl
from_json: '"' expected, at character offset 1 (before "blah}") at JSON.pm line 196.
at test_json.pl line 4.