Factoring try catch

cheb1k4 :

I have a Java EE application with dozens of web services using the same pattern:

public Response myWebService1() {
    try {
        // do something different depending on the web service called
    } catch (MyCustomException e1) {
        return Response.status(409).build();
    } catch (UnauthorizedException e2) {
        return Response.status(401).build();
    } catch (Exception e3) {
        return Response.status(500).build();
    }
}

Is that possible to factorize this piece of code?

T.J. Crowder :

If this is a JAX-RS environment, see Tunaki's answer, handling this is specifically catered for and wonderfully simple.

If not:

You can have a functional interface accepting a function that can throw exceptions and returns a Response:

@FunctionalInterface
public interface Responder {
    Response handleRequest() throws Exception;
}

(As Dici points out, you could make that a generic ThrowingSupplier or similar, since you're allowing it to throw Exception.)

Then have a helper method accepting an instance of it:

private static Response respond(Responder responder) {
    try {
        return responder.handleRequest();
    } catch (MyCustomException e1) {
        return Response.status(409).build();
    } catch (UnauthorizedException e2) {
        return Response.status(401).build();
    } catch (Exception e3) {
        return Response.status(500).build();
    }
}

...and use it via a lambda:

public Response myWebService1() {
    return respond(() -> {
        // Do stuff here, return a Response or throw / allow throws on error
    });
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=446655&siteId=1