Search code examples
javalambdavert.xfunctional-interface

Java lambda functions : a wrapper for a lambda function to with try-catch


I am looking for a lambda wrapper for the lambda function as explained in that post. But with a twist.

we have a lof methods that go:

private void method1(RoutingContext ctx, HttpClient client) {
    doAsync1(ctx, client, asyncResult -> {
        try {
            if (asyncResult.succeeded()) {

                ctx.response().setStatusCode(200).end();
            } else {
                LOG.error("doAsync1 failed", asyncResult.cause().getMessage());
                ctx.response().setStatusCode(500);
                ctx.response().end(asyncResult.cause().getMessage());
            }
        } catch (Exception ex) {
            LOG.error("error doAsync1 failed", ex);
            ctx.response().setStatusCode(500).end();
        }
    });
}

private void method2(RoutingContext ctx, HttpClient client) {
  //... async2 ...
}

I d like to get rid of the repetitive try-catch blocks by wrapping the lambda function in the handler. I got lost though.

How can i write a function, like the safely below, to simplify my methods?

doAsync1(ctx, client, safely(asyncResult -> {
            method1(ctx, httpClient);
        }));

(Though safely is probably a bad choice). It would take care of the error handling part.

 LOG.error("Failed in Parsing Json", e);
        ctx.response().setStatusCode(500);
        ctx.response().end(e.getMessage());

Here is the signature of the functional interface used in the handler of the methods like doAsync1

@FunctionalInterface
public interface Handler<E> {
    void handle(E var1);
}

Solution

  • a simple solution is as follows :

    private Handler<AsyncResult<String>> handleSafely(RoutingContext ctx, String method) {
        return asyncResult -> {
            ctx.response().headers().add("content-type", "application/json");
    
            try {
                if (asyncResult.succeeded()) {
                    ctx.response().setStatusCode(200).end(asyncResult.result());
                    LOG.info("asyncResult.succeeded()", asyncResult.result());
                } else {
                    LOG.error(method + " failed", asyncResult.cause().getMessage());
                    ctx.response().setStatusCode(500);
                    ctx.response().end(asyncResult.cause().getMessage());
                }
            } catch (Exception e) {
                LOG.error("error " + method, e);
                ctx.response().setStatusCode(500).end();
            }
        };
    }
    

    With that we can call :

    private void method1(RoutingContext ctx, HttpClient client) {
        method1(ctx, client, handleSafely(ctx, "method1"));
    }