morgon has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I need to map exceptions to error-codes (which will be embedded in a client-response).

Most of the exceptions are instances of Exception::Class-subclasses and the mapping is based on the class-name.

I curently do something like this:

my $rc; given($ex) { when($ex->isa("MyException::Class1")) { $rc = 1; } when($ex->isa("MyException::Class2")) { $rc = 2; } default { $rc = 3 } } # and now pass on $rc to a template
And I find that not very pleasing.

Is there a better way to do this?

Or can I do an isa-check via ~~

Many thanks!

Replies are listed 'Best First'.
Re: switch question
by roboticus (Chancellor) on Jan 06, 2011 at 23:46 UTC

    morgon:

    How about having a simple hash table then? Something like:

    my %XMap = ( 'MyException::Class1'=>1, 'MyException::Class2'=>2, ... ); sub errorcode { my $ex = shift; my $type = ref $ex; return $XMap{$type} if exists $XMap{$type} return 3; # default }

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: switch question
by lamprecht (Friar) on Jan 06, 2011 at 22:24 UTC

    Maybe your exception classes should implement errorcode()?

    Cheers Christoph
    BEGIN{ sub Exception::Class::Base::errorcode{ my %def = shift->_defaults; return $def{errorcode} ; } sub Exception::Class::Base::_defaults{ return (errorcode => 3); } } use Exception::Class ( 'MyException' => {defaults => {errorcode => 2} }, 'AnotherException' => { isa => 'MyException' }, 'YetAnotherException' => { isa => 'AnotherException', defaults => {errorcode => 5}, }, ); eval { YetAnotherException->throw( error => 'I feel funny.' ) }; my $e; if ( $e = Exception::Class->caught()){ warn $e->error, "\n"; warn $e->errorcode , "\n"; }
    update: example added
      Maybe your exception classes should implement errorcode()?
      I don't want to do that.

      I use this exceptions in other places as well where this mapping is irrelevant (or maybe I also need a mapping but a different one) and that in this particular case they are used to generate a return-code is not the concern of the exception-class.