Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello all- I have been using Net::FTP and Net::SFTP in a script that needs to keep running even when connection failures/timeouts/bad ip's are the case--but alas, Net::SFTP, for example, appears to die (and thus kill my script) whenever it fails to connect due to a timeout or a bad id/pass. I have tried a workaround like this, catching the DIE signal:
$SIG{__DIE__} = sub { if (!ref($_[0])) { $err = join('', @_); } print "error $err\n"; };
However, while the code above does execute, so I know the signal's been caught, the script still dies anyway. I also tried placing the code that uses the modules in an eval(), based on something else I read, but I get the same result. What can I do to keep my script running even when a module it uses wants to die? Thanks in advance, and sorry if I am missing an obvious answer (or am otherwise doing something obviously wrong). James

Replies are listed 'Best First'.
Re: How do I avoid a die generated by a module?
by broquaint (Abbot) on Jun 06, 2003 at 17:05 UTC
    The block version of eval should do it e.g
    eval { die "let's blow this joint!"; }; warn "ack - $@" if $@; __output__ ack - let's blow this joint! at - line 2.
    See. eval for more info.
    HTH

    _________
    broquaint

      That did it--not sure how I missed the block version of eval, but thank you very much for your help!! Now I just have to figure out where my understanding has gone wrong regarding my attempt to catch the DIE signal and handle it myself completely (i.e. do what I want with the error, including not dying if so I choose). James

        You can't catch and prevent a death using $SIG{__DIE__}. You have to use eval, as broquaint said. Once you've got the code that dies wrapped in an eval, all you need to do to "catch the DIE signal" is run the eval block, and then test to see if $@ is set, afterwards (as broquaint's code does with the warn). If it's set, then something in the eval block died. There's no way to prevent the code in the eval block from halting from the death. You just have to recover outside the block and then restart it, as needed. If you've ever used a language with exceptions (eg, Java), it's more like a try / catch pair, then catching and ignoring signals.

        Hope that makes it a little more clear.

        bbfu
        Black flowers blossom
        Fearless on my breath

Re: How do I avoid a die generated by a module?
by PodMaster (Abbot) on Jun 07, 2003 at 07:21 UTC
    `perldoc -f die' When dealing with a built-in perl function, perldoc -f -- How to RTFM


    MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
    I run a Win32 PPM repository for perl 5.6x+5.8x. I take requests.
    ** The Third rule of perl club is a statement of fact: pod is sexy.