Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
I want to return a Exception while my return type is Dto

If I couldn't find a user in my db with given id. I want to return an exception instead of null Dto, how can I do this?

public UserDto updateUser(Long id, UserDto userDto) {

    UserDto userDtoNew = null;

    if (userRepository.findById(id).isPresent()) {

        User existingUser = userRepository.findById(id).get();
        existingUser.setPassword(userDto.getPassword());
        existingUser.setUserName(userDto.getUserName());
        userDtoNew = userMapper.toDto(existingUser);

        return userDtoNew;
    }

    return userDtoNew;

}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

This is a terrible way to use a an Optional. Please learn how to properly use it.

return userRepository.findById(id)
 .map(it -> {
    it.setPassword(userDto.getPassword());
    it.setUserName(userDto.getUserName());
  }).map(userMapper::toDto)
  .orElseThrow(() -> new IllegalArgumentException("No user found for " + id));

Something along those lines is how to properly use an Optional and to throw an exception if nothing is found.

Ideally the thing called inside the map function/method is just a oneliner. So instead of having the code block with {} you might want to move that to a method to make it more readable.

private User update(User user, UserDto userDto) {
  user.setPassword(userDto.getPassword());
  user.setUserName(userDto.getUserName());
  return user;
}
return userRepository.findById(id)
 .map(it -> update(it, userDto))
 .map(userMapper::toDto)
 .orElseThrow(() -> new IllegalArgumentException("No user found for " + id));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!