in reply to How to return an appropriate error from module?
Example of what is inside Food::Productuse Food::Product; my $p = new Food::Product('Tomato') or die("Could not instance Food::Product: ($Food::Product::errstr)" +); $p->isle(14); $p->stock(450); $p->sell(450) or die($p->errstr); $p->sell(40) or die($p->errstr);
package Food::Product; use strict; use LEOCHARRE::Class2; # you do this your way use vars qw/$errstr/; __PACKAGE__->make_accessor_setget(qw/isle stock errst/); sub new { my($class,$arg)=@_; $arg or $errstr = "Missing valid arg" and return; return { name => $arg }, $class; } sub sell { my($self,$count)=@_; $count or $self->errstr('missing how much to sell ammount') and return; my $now = $self->stock or $self->errstr('no stock left to sell from') and return; my $left_over = ( $now - $count ) ... some other rationalle $self->stock($left_over); }
So in above examples.
Check out DBI, has some similarities.
I used to fumble with this, wondering if maybe $error was better a label.. but errstr is pretty freaking common.
So, to answer more directly. In c, it's common to return if something is up- in perl, we return when it's all good. So, store any messages in the class or object as a separate value. Do NOT assume the coder wants to access further information if something fails. Just make it possible to get more information. Whatever you do- don't return only if there's an error etc- that would be poor form in perl.
|
|---|