2013/12/06

Futures advent day 6

Day 6 - Control Flow with Failures

We have now seen how done is used to mark a Future as successfully complete thus causing its get method to return, and how then is used to create a chain of activity between them when they succeed. We have also seen how fail can be used to mark a Future as having failed thus causing its get method to throw the exception. We can complete this set of methods by adding else, which is used to chain an activity after a Future if it fails.

my $f = GET("http://my-site-here.com/a-page")
  ->else( sub {
    return Future->new->done(
      HTTP::Response->new( 599, "Failed", [], "GET failed" )
    );
  });

my $response = $f->get;

Here we are using else to act as a kind of try/catch block, taking any exception and turning it into a successful response instead. If the GET future returns successfully, the else code doesn't get to run; instead the success gets passed right through to $f.

<< First | < Prev | Next >

No comments:

Post a Comment