使用Perl的Try :: Tiny来捕获错误

时间:2012-12-31 19:34:16

标签: perl try-catch

我有以下代码:

99      if($host =~ /R3|R6/) {
100         #task 1.2 3 points
101         try {
102             my $ns = "http://xml.juniper.net/junos/$ver/junos-interface";
103             my $out = $jnx->get_interface_information(interface_name => "ae10")->toString();
104             my @ex_path = (["up","//x:oper-status"],["up","//x:admin-status"]);
105             my $ret = Check->checkt($ns,$out,@ex_path);
106             for(@{$ret}) {
107                 my $feed;
108                 $tasks[2]->[3]=$tasks[2]->[2] if $_->[0] == 0;
109                 $feed = $_->[2] if $_->[2];
110                 $feed = "Not Set" unless $_->[2];
111                 push @{$tasks[2]},"$host AE10 is currently $feed" if $_->[0] == 0;
112             }
113             my $datax = XML::LibXML::XPathContext->new(XML::LibXML->load_xml(string => $out));
114             $datax->registerNs("x",$ns);
115             my $minlinks = $datax->findvalue("//x:minimum-links-in-aggregate");
116             if($minlinks < 2) {$tasks[2]->[3]=$tasks[2]->[2]; push @{$tasks[2]},"$host does not currently have the minimum links set";}
117      } catch {
118             $tasks[2]->[3]=$tasks[2]->[2];
119             push @{$tasks[2]},"$host AE10 is currently not available";
120      };
121      }

我想抓住第103行产生的以下错误:

Can't call method "toString" on an undefined value at file.pm line 103, <> line 2.

并跳过try块的其余部分,执行catch块并保持脚本运行,但即使在try / catch添加到脚本之后它也没有这样做。

有谁知道我该怎么做?

1 个答案:

答案 0 :(得分:1)

没关系。我在包定义之上声明了Try :: Tiny。在我使用的供应商模块附带的ssh模块中出现了一些错误。