如何防止Perl脚本中的错误终止脚本?

时间:2009-08-15 12:44:28

标签: linux perl exception-handling daemon

我有一个简单的Perl脚本,它使用无限循环作为Linux守护程序运行。它每10秒连接一次数据库以执行一个进程。

while (1)
{
    # THIS LINE WILL KILL THE SCRIPT IF IT FAILS
    my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password");
    . . . do something . . .
    sleep (10);
}

我有两个问题:

  • 如果数据库不可用,我如何保持脚本运行?
  • 我可以添加例外处理程序向我发送电子邮件或记录错误吗?

3 个答案:

答案 0 :(得分:8)

这种尝试以10秒的间隔连接,而不是每隔10秒,就像William Pursell所指出的那样:

while (1)
{
    # THIS LINE WILL KILL THE SCRIPT IF IT FAILS
    my $DB;
    eval { 
        $DB = DBI->connect("dbi:Sybase:server=myserver","user","password");
    };
    if ( my $ex = $@ ) {
        warn $ex;
        next;
    }
    # do something with $DB
    continue {
        sleep 10;
    }
}

另请参阅Object Oriented Exception Handling in Perl, is it worth it?How can I cleanly handle error checking in Perl?

答案 1 :(得分:5)

我有点疑惑:

   my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password");
如果无法连接,

通常不会死亡。通常它应该返回错误代码 而不是数据库句柄。只有你使用RaisError才会死/抛出异常。

   my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password", 
                        { RaiseError => 1});

请参阅DBI man-page

答案 2 :(得分:1)

来自Programming Perl

sub try (&@) {
     my($try,$catch) = @_;
     eval { &$try };
     if ($@) {
         local $_ = $@;
         &$catch;
     }
}
sub catch (&) { $_[0] }

try {
    die "phooey";
} catch {
    /phooey/ and print "unphooey\n";
};