Skip to content

Commit

Permalink
fixed line numbers in Mojo::JSON error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Feb 19, 2014
1 parent 97511b9 commit 6a05f16
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 18 deletions.
3 changes: 2 additions & 1 deletion Changes
@@ -1,6 +1,7 @@

4.83 2014-02-20
4.83 2014-02-19
- Improved Mojo::JSON to handle encoding errors more gracefully.
- Fixed line numbers in Mojo::JSON error messages.

4.82 2014-02-19
- Added decode_json and encode_json functions to Mojo::JSON.
Expand Down
38 changes: 22 additions & 16 deletions lib/Mojo/JSON.pm
Expand Up @@ -2,6 +2,7 @@ package Mojo::JSON;
use Mojo::Base -base;

use B;
use Carp 'croak';
use Exporter 'import';
use Mojo::Util;
use Scalar::Util 'blessed';
Expand Down Expand Up @@ -43,15 +44,33 @@ my $WHITESPACE_RE = qr/[\x20\x09\x0a\x0d]*/;
sub decode {
my $self = shift->error(undef);

my $ref = eval { decode_json(shift) };
my $ref = eval { _decode(shift) };
return $ref if $ref;

chomp(my $e = $@);
$self->error($e);
$self->error(_chomp($@));
return undef;
}

sub decode_json {
eval { _decode(shift) } // croak _chomp($@);
}

sub encode { encode_json($_[1]) }

sub encode_json { Mojo::Util::encode 'UTF-8', _encode_value(shift) }

sub false {$FALSE}

sub j {
return encode_json($_[0]) if ref $_[0] eq 'ARRAY' || ref $_[0] eq 'HASH';
return eval { _decode($_[0]) };
}

sub true {$TRUE}

sub _chomp { chomp $_[0] ? $_[0] : $_[0] }

sub _decode {

# Missing input
die "Missing or empty input\n" unless length(my $bytes = shift);
Expand Down Expand Up @@ -89,19 +108,6 @@ sub decode_json {
return $ref;
}

sub encode { encode_json($_[1]) }

sub encode_json { Mojo::Util::encode 'UTF-8', _encode_value(shift) }

sub false {$FALSE}

sub j {
return encode_json($_[0]) if ref $_[0] eq 'ARRAY' || ref $_[0] eq 'HASH';
return eval { decode_json($_[0]) };
}

sub true {$TRUE}

sub _decode_array {
my @array;
until (m/\G$WHITESPACE_RE\]/gc) {
Expand Down
2 changes: 1 addition & 1 deletion t/mojo/json.t
Expand Up @@ -379,7 +379,7 @@ is $json->error,
'right error';
is j('{'), undef, 'decoding failed';
eval { decode_json("[\"foo\",\n\"bar\",\n\"bazra\"]lalala") };
like $@, qr/Malformed JSON: Unexpected data after array at line 3, offset 8/,
like $@, qr/JSON: Unexpected data after array at line 3, offset 8 at.*json\.t/,
'right error';

done_testing();

0 comments on commit 6a05f16

Please sign in to comment.