Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've wrapped Perl's Net::SSH::Expect with a small module to reduce the boilerplate code needed to write a new configuration script for use with our HP iLO cards. While on one hand I want this wrapper to be as lean as possible, so non-programmer colleagues can use it, I also want it to be as well-written as possible.

It's used like so:

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 is 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;
    }
}

I have two related queries. First, how should I deal with responses that don't match the expected response? I guess what I'm doing now is satisfactory -- by returning undef I signal something broke and my croak() will output an error (though hardly gracefully). But it feels like a code smell. If Perl had exceptions I'd raise one and let the calling code decide whether or not to ignore it/quit/print a warning, but it doesn't (well, in 5.8). Perhaps I should return some other object (iLO::response, or something) that carries an error message and the contents of $ilo->before() (which is just Net::SSH::Expect's before())? But if I do that -- and have to wrap every $ilo->command in a test to catch it -- my scripts are going to be full of boilerplate again.

Secondly, what should I return for success? Again, my hash containing more-or-less the response from Net::SSH::Expect does the job but it doesn't feel 'right' somehow. Although this example's in Perl my code in other languages emits the same familiar smell: I'm never sure how or what to return from a method. What can you tell me?

like image 405
markdrayton Avatar asked Jan 09 '09 21:01

markdrayton


People also ask

How do you handle in Perl?

The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent Standard Input, Standard Output, and Standard Error devices respectively. File Handling is usually done through the open function. Syntax: open(FileHandle, Mode, FileName);

What is error handling method?

Error handling refers to the response and recovery procedures from error conditions present in a software application. In other words, it is the process comprised of anticipation, detection and resolution of application errors, programming errors or communication errors.

How do I raise an exception in Perl?

How exception works in Perl? You could use a try-catch block using Nice::Try. Nice::Try also handles exception class, so you could catch an exception based on the exception class used.


2 Answers

If you're familiar with exceptions from languages like Java, then think of die as throw and eval as try and catch. Instead of returning undef, you could do something like this:

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();

Then, in your calling code:

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

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

Just like exceptions in other languages, this allows you to bail out of a submethod at any point without having to worry about propagating return values up the call stack. They'll be caught by the first eval block that finds them. Additionally, you can die again to rethrow an exception you can't deal with back up the stack.

Even better, you can use die to throw an object, which your exception handler can interrogate for useful information and error messages. I like to use Exception::Class for this purpose. The Error module provides some syntactic sugar for doing Java-like try/catch blocks, as well.

like image 52
friedo Avatar answered Sep 23 '22 15:09

friedo


The usual way to raise exceptions in Perl is with die. The usual way to catch them is using eval with a block as an argument, and testing $@ after the eval finishes.

like image 28
Andru Luvisi Avatar answered Sep 24 '22 15:09

Andru Luvisi