samedi 17 décembre 2016

handling application and business failure scenarios for a java REST API using exceptions

I am developing a Java application and in my resource class I have all JAX-RS API methods defined. Also I am using dependency injection in my resource class to delegate each task to its own service class:

class Resource {

    // Services are injected.
    // Each service has a couple of failure scenarios.
    // Exp. Request Not valid, Id not valid, Database internal error, etc.
    DBService dbService;
    validationService validationService;
    searchService searchService;

    @GET(user/:id)
    public User getUser(int id) {
        try {
            validationService.validate(request);
            dbService.getUser(id);
            searchService.index(request);
            ...
        } catch (UserNotFoundException e) {
            // return proper http response code and message
        } catch (UserNotFoundException e) {
            ...
        } catch (UserNotFoundException e) {
            ...
        } ... 

    }
}

For each of failure scenarios in each Service class I am creating a specific Exception for that failure scenario and throwing it in Service class and handling all of these exceptions in API Resource class. I am using Exception as a signal to my Resource about failure scenario and return proper HTTP status code and message.

A complain I am getting is that I am creating a lot of Exception classes and my Resource class has a long list of catch blocks for different failure scenarios.

One suggested solution was that for example in my validationService I return a false boolean instead of exception and in my resource I put an if/else statement and return proper status code. However I don't like this solution because it makes my api full of if/else statements and less linear.

My question is , is it OK to have many exception classes for my use case and is there any better architecture for my use?

Aucun commentaire:

Enregistrer un commentaire