Home > Mobile >  I want to return a Exception while my return type is Dto
I want to return a Exception while my return type is Dto

Time:04-13

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;

}

CodePudding user response:

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));
  • Related