Come faccio a gestire sia gli errori catturati e non gestite fanno in una subroutine Perl?

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

  •  22-08-2019
  •  | 
  •  

Domanda

Questo è un follow-up a " Come posso andare in giro a 'morire' chiamo in una libreria Perl non posso modificare? ".

Ho una subroutine che chiama una Biblioteca-Quali-Crash-A volte molte volte. Invece di divano ogni chiamata all'interno di questa subroutine con un eval {}, ho solo permettono di morire, e utilizzare un eval {} al livello che chiama il mio subroutine:

my $status=eval{function($param);};
unless($status){print $@; next;}; # print error and go to
                                  # next file if function() fails

Tuttavia, ci sono condizioni di errore che posso e mi cattura in funzione di (). Qual è il / modo elegante più proprio per progettare l'errore-catching nella subroutine e la routine di chiamare in modo che ottengo il comportamento corretto per gli errori sia catturati e non gestite fanno?

È stato utile?

Soluzione

Blocca eval può essere nidificato:

sub function {
    eval {
        die "error that can be handled\n";
        1;
    } or do {
        #propagate the error if it isn't the one we expect
        die $@ unless $@ eq "error that can be handled\n"; 
        #handle the error
    };
    die "uncaught error";
}

eval { function(); 1 } or do {
    warn "caught error $@";
};

Altri suggerimenti

Non sono del tutto sicuro di quello che si vuole fare, ma credo che si può fare con un gestore.

$SIG{__DIE__} = sub { print $@ } ;

eval{ function($param); 1 } or next;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top