Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Creating exception classes

by Athanasius (Abbot)
on Feb 05, 2013 at 02:35 UTC ( #1017046=note: print w/ replies, xml ) Need Help??


in reply to Creating exception classes

The problems are not in the declaration, but in sub ThrowMyException. Here is a working version, with changes commented:

#! perl use strict; use warnings; use Exception::Class ( 'MyException', Commands => { isa => 'MyException', }, Timeout => { isa => 'Commands', description => 'This exception results from running the metric +s commands', }, DBError => { isa => 'MyException', description => 'DB returned error', }, ); ThrowMyException(); print "No error caught\n"; sub ThrowMyException # NO prototype { eval { Timeout->throw # NOT MyException::Commands::Timeo +ut-> ( error => "This error is due to a timeout" ); }; my $err; if ($err = Exception::Class->caught('Timeout')) { die $err->description . # NOT $err->{"description"} ': ' . $err->error; # NOT $err->{"error"} } elsif ($err = Exception::Class->caught('MetricsException')) { die $err->error; } else { $err = Exception::Class->caught(); ref $err ? $err->rethrow : die $err; } }

Output:

12:30 >perl 517_SoPW.pl This exception results from running the metrics commands: This error i +s due to a timeout at 517_SoPW.pl line 56. 12:33 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


Comment on Re: Creating exception classes
Select or Download Code
Re^2: Creating exception classes
by perlbaski (Sexton) on Feb 05, 2013 at 18:48 UTC
    Thanks, that worked..I was thinking classes are blessed hashes, so I was trying to access them that way, looks like Exception::Class module creates accessors to access the fields. Am I correct?

      From the source code it appears that Exception::Class inherits from Exception::Class::Base. The documentation for Exception::Class::Base catalogues a number of class and/or object methods, among which are these:

      MyException->description()
      Returns the description for the given Exception::Class::Base subclass. ... This is also an object method.

      $exception->error()
      Returns the error/message associated with the exception.

      So these accessors are, as it were, “built-in” to any class derived from Exception::Class.

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1017046]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2015-07-03 04:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (48 votes), past polls