NAME

Sub::Attempts - alter subroutines to try again on exceptions

SYNOPSIS

use Sub::Attempts;

sub alter_db
{
  my $dbh = DBI->connect("DBD::Mysql:foo", "mark", "opensaysme")
    or die "Can't connect to database";
  $dbh->{RaiseException} = 1;
  $dbh->do("alter table items change pie pies int(10)");
}

# if there's a problem making pies, wait and try again
attempts("alter_db", tries => 3, delay => 2);

DESCRIPTION

Sometimes if a subroutine throws an exception the right thing to do is wait for a while and then call the subroutine again, as the error conditions that caused the subroutine to have to throw the exception might have gone away.

This module exports one subroutine attempts which can be used to modifiy existing subroutines so that whenever that subroutine is called it will be automatically be called again in the event that it throws an exception.

use LWP::Simple qw(get);
sub journal_rss
{
  return get("http://use.perl.org/~2shortplanks/journal/rss")
    or die "Couldn't get journal";
}
attempts("journal_rss");

By default perl will attempt to run to run the subroutine again without delay if an exception is thrown. If on the second run an exception is again thrown, that exception will be propogated out of the subroutine as normal.

The particulars of the subroutines re-execution can be changed by passing extra parameters to attempts. The tries parameter effects the number of times the subroutne will attempt to be executed. The delay parameter determines how long perl will wait - sleep - in seconds (and fractions of a second) between execution attempts.

Methods

A method can be modified just like any other subroutine, provided the subroutine defining the method is located in the same package as attempts is called from. If this is not the case (i.e. the method is inherited and not overridden) then you should use the method parameter:

attempts("get_pie", tries => 3, method => 1);

This has the same effect as writing:

sub get_pie
{
  my $self = shift;
  $self->SUPER::get_pie(@_);
}

attempts("get_pie", tries => 3);

If a method is defined by a subroutine in the current package then the method parameter has no effect

AUTHOR

Written by Mark Fowler <mark@twoshortplanks.com>

Copryright Mark Fowler 2003. All Rights Reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

BUGS

Though list and scalar context will be preserved for the call to the original subroutine, other forms of context (as offered by Want) will be lost. Therefore, amongst other things, a subroutine modified by attempts cannot currently 1be used as a lvalue.

The caller bug is now defeated, thanks to Sub::Uplevel things think they're in a higher caller frame.

Bugs should be reported to me via the CPAN RT system. http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sub::Attempts.

SEE ALSO

Attribute::Attempts, Attempt