Dear monks,
I've got another question regarding the same topic of "handling errors" and your help would be really appreciated. This time I'm thinking about the best way of passing the stacktrace from the deepest bottom to the top caller.
I'd better explain my question by some example. Let's assume, we have some some classes and some methods:
package ClassB; sub method_y { if($something_has_gone_wrong) { confess("Something has gone wrong!"); } } package ClassA; sub method_x { try { $class_b_object->method_y; } catch { confess($_); } } package main; try { $class_a_object->method_x } catch { $log->error($_); }
I need to have a stack-trace to be delivered to the main module, but, obviously, when something goes wrong, I have 2 stack-traces instead of 1 (one is from ClassA::method_x and another - from ClassB::method_y), which is really ugly. I need only the stack-trace from the bottom, but I don't want to decide whenever I shall die() or confess() in every catch-block.
As a solution, I imagine something like that:
package Error; sub new { my($self, $class, $parameter) if(ref($parameter) eq 'Error') { return($parameter); } else { bless($self, $class); $self->stacktrace(Devel::StackTrace->new->as_string); $self->message($parameter); $self->timestamp(time); $self->whatever("Blah-blah"); return($self); } } package ClassB; sub method_y { if($something_has_gone_wrong) { die(Error->new("Something has gone wrong")); } } package ClassA; sub method_x { try { $class_b_object->method_y } catch { die(Error->new($_)); } } package main; try { $class_a_object->method_x; } catch { if(ref($_) eq Error) { print(SOMEWHERE "The worst has happened at " . $_->timestamp . "\n +"); print(SOMEWHERE $_->message . "\n"); print(SOMEWHERE $_->backtrace . "\n"); } else { $log->error($_); } }
So, the deepest subroutine (ClassB::method_y) dies and creates a new Error-object, which has a stacktrace and everything else we need. This object is being passed as $_ to the constructor of another Error-object inside of ClassA::method_x, but it won't add anything to this object, because it will understand that it have got an Error-object, not just an error-message. Then the main module will do something with that object.
I'm not sure about this idea, so I'll be glad to know your opinion on that.
Thank you very much!
In reply to Who should generate a stacktrace by v_melnik
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |