简体   繁体   中英

Handling Exceptions in Repository Layer

This code fails when performing JUnit Mock tests. The exceptions in the method definition (NoResultException, PersistenceException) do not match those that are actually returned by the method (UnknownEntityException, ServiceException). Is this just an obvious error?

The project exceptions (UnknownEntityException, ServiceException) were supposedly created so that there would be a common way to handle exceptions. The original code's creators are long gone and I cannot determine whether this is even a good idea.

@Repository
public class InstitutionRepository {

    @PersistenceContext
    private EntityManager entityManager;

    public EntityInstitutionModel findInstitutionByName(String instName) 
            throws NoResultException, PersistenceException {        
        try {
            Query query = null;
            query = entityManager.createQuery("SELECT ex from EntityInstitutionModel ex where ex.instname = :instName");
            query.setParameter("instName", instName);

            EntityInstitutionModel instModel = (EntityInstitutionModel) query.getSingleResult();

            System.out.println("InstitutionRepository.findInstitutionByName.getId() = " + instModel.getId());

            return instModel;

        }catch (NoResultException e) {
            throw new UnknownEntityException(e);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}

There's no error here; the exceptions PersistenceException and NoResultException are both runtime exceptions, which means that they don't need to be declared, and as such, even if they weren't thrown, would allow the code to compile anyway.

My advice would be to remove the throws clause from your method, since that's only serving to confuse and frustrate you as a maintainer.

(Also, if you can do something about that catch Exception at the end, that'd be good too; don't want to go catching things you really shouldn't be down there.)

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