Search code examples
jsonperlload-testingstderr

How can I catch a "failed to decode JSON" error message in Perl?


So I am trying to load test a REST API which returns a JSON value.

To do that I am creating multiple instances of the perl script.

The Perl script basically calls that URL, and tries to decode_json. Obviously when substantial load is generated, it fails.

Now the problem I face is- An error is displayed on command prompt but does not write that error message in a file.

The error message is

malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "Can't connect to 209...") at json_load_test.pl line 39.

In all the three attempts below line 39 refers to:

decode_json($actual_response);

I am simply running the script on the command prompt as:

perl json_load_test.pl >> logs/output.txt 

I EXPECT THE ERROR MESSAGE TO BE WRITTEN IN "output.txt"

My three failed attempts are as follows.

Attempt 1:

my $ua = LWP::UserAgent->new;
$ua->timeout(3);    
$ua->env_proxy;        
my $response = $ua->get("http://$j_env/jobs/all.json?status=active");
my $actual_response=$response->decoded_content;
decode_json($actual_response);
if ($? == -1)
{print "\n Failed to execute: $!\n"; }

Attempt 2:

my $ua = LWP::UserAgent->new;
$ua->timeout(3);    
$ua->env_proxy;        
my $response = $ua->get("http://$j_env/jobs/all.json?status=active");
my $actual_response=$response->decoded_content;
my $perl_scalar= decode_json($actual_response);
if ($perl_scalar)
{ok(1,"For process $u2 inside counter $counter ");}
else
{ok(0,"FAILED!!! process $u2 inside counter $counter");}

Attempt 3:

my $ua = LWP::UserAgent->new;
$ua->timeout(3);    
$ua->env_proxy;        
my $response = $ua->get("http://$j_env/jobs/all.json?status=active");
my $actual_response=$response->decoded_content;
decode_json($actual_response) or die "FAILED!!!!";

Solution

  • It looks like your error message is coming from stderr, not stdout. Thus,

    perl json_load_test.pl >> logs/output.txt 2>> logs/errors.txt
    

    Or something to that effect. If you want both in one file:

    perl json_load_test.pl 2>&1 >> logs/output.txt
    

    EDIT:

    If for some reason you wanted to trap the error in the perl and send it to stdout, you could:

    eval {
      decode_json($actual_response);
      1;
    } or do {
      my $e = $@;
      print "$e\n";
    };
    

    EDIT2:

    As daxim points out in the edit notes, Try::Tiny may be simpler:

    use Try::Tiny;
    try {
      decode_json($actual_response);
    } catch {
      print "$_\n";
    };