v_melnik has asked for the wisdom of the Perl Monks concerning the following question:
I have the error attribute for every class for explaining to the caller what's gone wrong. And the caller should do:
my $result = $object->method(); unless(defined($result)) { $log->error("Something's gone wrong when called $object->method(): + " . $object->error_message); # ...doing something with that... }
When I need to return undef as a result (for example, if the method hasn't found the result - not because of an error occuried), I have to do something like that:
my $result = $object->method(); if($object->has_error) { $log->error("Something's gone wrong when called $object->method(): + " . $object->error_message); # ...doing something with that... } # ...doing something else, understanding that the method just doesn't +have anything to pass to us...
Are there people who prefer to pre-suppose all their methods are dying every time when something goes wrong, so all methods should be called through eval{}/try{}/...?
Sometimes I'm thinking about it as about a better way. For example it would allow me to return undef when nothing wrong have happened, so I'd prefer to die() with some explaination that would be accessible as the $@ variable.
So I consider about something that would look like that:
my $result = eval { $object->method() }; if($@) { $log->error("Something's gone wrong when called $object->method(): + $@"); # ...doing something with that... } # ...doing something else, understanding that the method just doesn't +have anything to pass to us...
Maybe it would be better to try some of TryCatch mechanisms from CPAN.
Anyway, using die() from the method really looks a bit odd. Who really does that? Have you been always doing it that way or started to do it that way some time ago?
Thank you!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using die() in methods
by moritz (Cardinal) on Jul 06, 2014 at 16:47 UTC | |
|
Re: Using die() in methods
by boftx (Deacon) on Jul 06, 2014 at 17:21 UTC | |
by Laurent_R (Canon) on Jul 06, 2014 at 20:27 UTC | |
|
Re: Using die() in methods
by Anonymous Monk on Jul 06, 2014 at 17:17 UTC | |
|
Re: Using die() in methods
by Anonymous Monk on Jul 06, 2014 at 20:55 UTC | |
|
Re: Using die() in methods
by tobyink (Canon) on Jul 07, 2014 at 13:47 UTC | |
by v_melnik (Scribe) on Jul 07, 2014 at 18:23 UTC | |
by tobyink (Canon) on Jul 09, 2014 at 22:33 UTC | |
by boftx (Deacon) on Jul 08, 2014 at 02:37 UTC | |
|
Re: Using die() in methods
by perlfan (Parson) on Jul 07, 2014 at 11:50 UTC |