Exception::Class



examples/error/exception.pl
#!/usr/bin/perl
use strict;
use warnings;

use English qw( -no_match_vars ) ;
use Carp qw(croak carp);
use Lottery qw(add_lottery_numbers);

# Catching exceptions
eval {
    add_lottery_numbers(@ARGV);
};
if ($EVAL_ERROR) {
    if (Number::Missing->caught) {
        print "$EVAL_ERROR\n";
        print "Usage: $0 NUMBERs  (at least 2 numbers are needed)\n";
        exit;
    }
    if (Number::Small->caught() or Number::Big->caught) {
        print "$EVAL_ERROR\n";
        print "Numbers must be between 1-90\n";
        exit;
    }

    # error that I don't know how to handle:
    croak $EVAL_ERROR;
}
print "Number was ok\n";

examples/error/Lottery.pm
package Lottery;
use strict;
use warnings;

use Lottery::Exceptions;
use Exporter qw(import);
our @EXPORT = ('add_lottery_numbers');

# Throwing exceptions
sub check_number {
    my ($num) = @_;

    if ($num < 1) {
        Number::Small->throw(number => $num);
    }
    if ($num > 90) {
        Number::Big->throw(number => $num);
    }
}

sub add_lottery_numbers {
    my (@numbers) = @_;

    if (@numbers < 2) {
        Number::Missing->throw();
    }

    foreach my $n (@numbers) {
       check_number($n);
    }
    submit_numbers(@numbers);
}

sub submit_numbers {
}

1;

examples/error/Lottery/Exceptions.pm
use Exception::Class (
    'Number::Small' => {
        fields => [ 'number' ],
    },
    'Number::Big' => {
        fields => [ 'number' ],
    },
    'Number::Missing' => {},
);

sub Number::Small::full_message {
    my ($self) = @_;
    return "number " . $self->number . " is too small";
}

sub Number::Big::full_message {
    my ($self) = @_;
    return "number " . $self->number . " is too big";
}
sub Number::Missing::full_message {
    my ($self) = @_;
    return "a number is missing";
}

1;