Skip to content

Instantly share code, notes, and snippets.

@schaloner
Created March 28, 2014 13:44
Show Gist options
  • Save schaloner/9833073 to your computer and use it in GitHub Desktop.
Save schaloner/9833073 to your computer and use it in GitHub Desktop.
Handling exceptions in Play 2 Java asynchronous controllers. Thinking about ways of specifying Result types from within async blocks.
package controllers;
import play.libs.Akka;
import play.libs.F;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.concurrent.Callable;
public class AsyncApplication extends Controller {
public static Result synchronousCall() {
String foo = intensiveOperationA();
String bar = intensiveOperationB();
return ok("Got result: " + foo + " " + bar);
}
public static Result asynchronousCall_asPerPlayDocs() {
F.Promise<String> promise = Akka.future(new Callable<String>() {
@Override
public String call() throws Exception {
String foo = intensiveOperationA();
String bar = intensiveOperationB();
return foo + " " + bar;
}
});
return async(promise.map(new F.Function<String, Result>() {
@Override
public Result apply(String s) throws Throwable {
// what if we want something other than 200?
return ok("Got result: " + s);
}
}));
}
public static Result asynchronousCall_possibleAlternative() {
F.Promise<Result> promise = Akka.future(new Callable<Result>() {
@Override
public Result call() throws Exception {
Result result;
String foo = intensiveOperationA();
if (foo.equals("hurdy")) {
result = badRequest("Something went wrong");
} else {
String bar = intensiveOperationB();
result = ok("Got result: " + foo + " " + bar);
}
return result;
}
});
return async(promise);
}
private static String intensiveOperationA() {
return "foo";
}
private static String intensiveOperationB() {
return "bar";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment