How should I handle errors in Perl methods and what should I return from methods?

I wrapped Perl Net :: SSH :: Expect with a small module to reduce the template code needed to write a new script configuration for use our HP iLO cards . Although, on the one hand, I want this wrapper to be as thin as possible, so colleagues who are not programmers can use it, I also want it to be written as well as possible.

Used like this:

my $ilo = iLO->new(host => $host, password => $password);
$ilo->login;

$ilo->command("cd /system1");
$ilo->command("set oemhp_server_name=$system_name", 'status=0');

and this iLO::command():

sub command {
    my ($self, $cmd, $response) = @_;

    $response = 'hpiLO-> ' unless defined($response);

    # $self->{ssh} is a Net::SSH::Expect object
    croak "Not logged in!\n" unless ($self->{ssh});

    $self->{ssh}->send($cmd);
    if ($self->{ssh}->waitfor($response, $self->{CMD_TIMEOUT}, '-re')) {
        return {
            before => $self->{ssh}->before(),
            match => $self->{ssh}->match(),
            after => $self->{ssh}->after(),
        };
    } else {
        carp "ERROR: '$cmd' response did not match /$response/:\n\n",
            $self->{ssh}->before()),
            "\n";
        return undef;
    }
}

. -, , ? , , , - undef, - , croak() ( ). . Perl , , , // , (, 5.8). , - (iLO::response - ), $ilo->before() ( Net:: SSH:: Expect before())? - $ilo->command , - .

-, ? , , Net:: SSH:: Expect, , "". Perl, : , . ?

+5
4

, Java, die throw eval try catch. undef - :

if ($self->{ssh}->waitfor($response, $self->{CMD_TIMEOUT}, '-re')) {
    return {
        before => $self->{ssh}->before(),
        match => $self->{ssh}->match(),
        after => $self->{ssh}->after(),
    };
}

die "ERROR: '$cmd' response did not match /$response/:\n\n" 
. $self->{ssh}->before();

:

eval { 
    $ilo->command("set oemhp_server_name=$system_name", 'status=0');
};

if ( my $error = $@ ) { 
    # handle $error here
}

, , . eval , . , die , .

, die , . Exception:: Class . Error Java- try/catch.

+5

Perl - die. - eval $@ eval.

+5

googlespace. , , , , , . , . , , .

Perl CPAN ( , ), , . Perl, - . , : " ".

. , , . , . ( )? , , .

, , . , ? die eval. , . ? , script, , , . , , .

, , 2d6.:)

+4

In addition to using the “die” exception as an exception, you can also add another method:

if (!$ilo->commandSucceeded("set oemhp_server_name=$system_name", 'status=0')) {
     #recover here
}

Of course, the internal implementation of the () command becomes

die ... if !commandSucceeded;
0
source

All Articles