gpt4 book ai didi

json - 如何在Perl中捕获 "failed to decode JSON"错误消息?

转载 作者:行者123 更新时间:2023-12-04 03:02:06 25 4
gpt4 key购买 nike

因此,我正在尝试加载测试返回JSON值的REST API。

为此,我正在创建perl脚本的多个实例。

Perl脚本基本上会调用该URL,然后尝试decode_json。显然,当产生大量负载时,它就会失败。

现在,我面临的问题是-命令提示符上显示了一个错误,但未在文件中写入该错误消息。

错误消息是
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.
在第39行下面的所有三种尝试中,均指:

decode_json($actual_response);

我只是在命令提示符下以以下方式运行脚本:
perl json_load_test.pl >> logs/output.txt 

我期望在“output.txt”中写入错误消息

我的三个失败尝试如下。

尝试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"; }

尝试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");}

尝试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!!!!";

最佳答案

看来您的错误消息来自stderr,而不是stdout。因此,

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

或类似的东西。如果您希望两者都在一个文件中:
perl json_load_test.pl 2>&1 >> logs/output.txt

编辑:

如果出于某种原因您想将错误捕获到perl中并将其发送到stdout,则可以:
eval {
decode_json($actual_response);
1;
} or do {
my $e = $@;
print "$e\n";
};

编辑2:

正如daxim在编辑说明中指出的,Try::Tiny可能更简单:
use Try::Tiny;
try {
decode_json($actual_response);
} catch {
print "$_\n";
};

关于json - 如何在Perl中捕获 "failed to decode JSON"错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7809740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com