Home > Back-end >  Optional IncorrectResultSizeDataAccessException
Optional IncorrectResultSizeDataAccessException

Time:11-25

public Optional<Student> findStudent(String name, String` surname,String nickname)
         {

    try {

       return repository.findOne(predicates.hasSpecifications(name, String surname,nickname));

    } catch (IncorrectResultSizeDataAccessException e) {

        return Optional.empty();
    }

}

the method findOne() throws IncorrectResultSizeDataAccessException if more than one entry is found for the predicate inside of it. Is this the best way to handle the exception thrown? or should the caller handle the exception using something like: optional.orElseThrow()... but this method only handles NoSuchElementException (if no value is present) and not IncorrectResultSizeDataAccessException (If more than 1 RESULT)...

Any ideas guys?

CodePudding user response:

Yeah, this would be the best way to do it.

I'm assuming hasSpecifications is a custom method which returns the id you wish to use to index the database The thing is "findOne" and "hasSpecifications" are two methods independent of each other. When we talk about abstraction, in methods then the only things that matter are their input parameters, the return values and the errors that may or may not be thrown.

This means "findOne" only cares about what "hasSpecifications" evaluates to. If there is an error or exception thrown while "hasSpecifications" is still executing then this error abruptly terminates the program (unless caught) and findOne wont even be evaluated (Because it was waiting for the id). A NoSuchElementException cannot be thrown because findOne hadn't started executing yet.

So since it's a custom method, the error handling has to be done by you, as you just did.

To make it more obvious extract predicates.hasSpecifications into a variable on a preceeding line and then place the variable in "findOne"

  • Related