http://qs321.pair.com?node_id=184203


in reply to Re: What Are The Rules For Subs And Modules When Fed Wrong Input
in thread What Are The Rules For Subs And Modules When Fed Wrong Input

I agree with the above error-handling technique. I hate to have a module die on me, ever. I also hate wrapping every call to a method in eval { } to assure that it doesn't die, and I want my logic to be able to know when there's been an error, not my user. The only points I would add would be to use an error method rather than variable, which gives the author / user some control (if they wish) over how the error is reported, and to make all methods return undef() on failure so that the person utilizing the module has a consistant activity for determining if an error occured. Any method that doesn't return data should return true (1), so that the user could say :

if($object->method) { .. } else { my $error = $object->error(); }

e.g.:

sub foo { my($self,$arg) = @_; if( !defined($arg) ) { $self->error("[mymodule::foo] Required Argument, ARG, not supplied +.\n"); return(undef); } else { return(1); } }

As a note for configurable error-handling methods, you could do something like this:

sub error { my $self = shift; if( defined($_[0]) ) { $self->{'Error'} = $_[0]; if( $self->raise_error() ) { warn("$_[0]\n"); } if( $self->die_error() ) { die("$_[0]\n"); } } return($self->{'Error'}); }

So there, you have a method that can be used both as an private method (for setting the error) and a public method (retrieving the error), with the ability for the user to configure how they get their errors back, as a scalar, a call to warn, or a call to die.

Now, you'd also want to give them a method for configuring that activity, you could either do it via options when creating a new instance of the module, or you could give them method(s) like the following, which also handle the lookups for the error() method:

sub raise_error { my $self = shift; $self->{'Raise'} = $_[0] if( defined($_[0]) ); return($self->{'Raise'}); }

There, now you've got these methods that have both public and private interfaces, that effectivly handle whatever the user desires, but by default (you could set them to) require checks on return values and lookups with a method...


!c