简体   繁体   中英

JavaEE EntityManager exception handling

I'm working on my DAO and can't figure out what's the best way to handle exceptions. While using the .persist() there are 3 exceptions that can be emitted : EntityExistsException / IllegalArgumentException / TransactionRequiredException.

I'm just wondering what's the best way to catch and throw the exception (I want to handle it on a higher level).

Should I catch and throw a simple exception or is it more efficient to catch the above exceptions separately ?

First method, I just catch Exceptions and throw it:

public void addAccount(final Account accountToAdd) throws AccountJpaException {

    try {
        em.persist(accountToAdd);
    } catch (Exception e) {
        throw new AccountJpaException(e);
    }

  }
}

Second method : I catch every one of them separately

public void addAccount(final Account accountToAdd) throws AccountJpaException, AccountExistsException {

    try {
        em.persist(accountToAdd);
    } catch (EntityExistsException e) {
        throw new AccountExistsException(e);
    }catch(IllegalArgumentException e){
        throw new AccountJpaException(e);
    }catch(TransactionRequiredException e){
        throw new AccountJpaException(e);
    }

  }
}

Thank you for your advices!

Most N-tier applications specify some transaction boundary on a service class. It would be more appropriate to catch these types of exceptions there and throw use case specific exceptions here rather than pushing this logic handling down to the DAO.

Consider for the moment a DAO method is used by two different service class implementations. Its conceivable that they address different concerns in your business domain and so the exceptions to be thrown should be more domain-specific.

If we took your second approach, you'd be catching those exceptions and throwing some super generic exception from the DAO only to catch those exceptions and re-throw a more granular exception at the service level, which is overkill.

My rule of thumb has been catch these types of cases at the service/domain level, propagate domain specific exceptions from there and handle those exceptions in the controllers as needed, perhaps by some specific error handler that displays the appropriate web page view based on exception types, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM