How can I prevent my perl script from terminating if an exception is thrown in a module it uses?

StackOverflow https://stackoverflow.com/questions/8344551

  •  27-10-2019
  •  | 
  •  

Pergunta

I have a perl script, using standard-as-dirt Net::HTTP code, and perl 5.8.8. I have come across an error condition in which the server returns 0 bytes of data when I call:

$_http_connection->read_response_headers;

Unfortunately, my perl script dies, because the Net::HTTP::Methods module has a "die" on line 306:

Server closed connection without sending any data back at
/usr/lib/perl5/vendor_perl/5.8.8/Net/HTTP/Methods.pm line 306

And lines 305-307 are, of course:

unless (defined $status) {
die "Server closed connection without sending any data back";
}

How can I have my script "recover gracefully" from this situation, detecting the die and subsequently going into my own error-handling code, instead of dieing itself?

I'm sure this is a common case, and probably something simple, but I have not come across it before.

Foi útil?

Solução

You can use eval { } to catch die() exceptions. Use $@ to inspect the thrown value:

eval {
    die "foo";
};
print "the block died with $@" if $@;

See http://perldoc.perl.org/functions/eval.html for details.

Outras dicas

Using eval to catch exceptions can occasionally be problematic, especially pre 5.14. You can use Try::Tiny.

Customizing the die to mean something else is simple:

sub custom_exception_handler { ... } # Define custom logic

local $SIG{__DIE__} = \&custom_exception_handler;  # Won't die now
# Calls custom_exception_handler instead

The big advantage of this approach over eval is that it doesn't require calling another perl interpreter to execute the problematic code.

Of course, the custom exception handler should be adequate for the task at hand.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top