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.
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"; }
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");}
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!!!!";
The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable. Syntax: json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )
Decoding JSON in Perl (decode_json) Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type.
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";
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With