Google Apps Script; Exception: Cannot retrieve next object: the iterator has reached the end

I’m trying to iterate in diferents rows to collect data from users that have answered a Google forms and generate diferent documents with their data. So far I’ve acomplished that part of my code, but there’s a problem when I try to classifie their documents in several folders. It’s like a hierarchy that starts classifing form their course (highschool), and then from their class (A, B…), but i only get this exception.

Exception: Cannot retrieve next object: the iterator has reached the end.

And I don’t know what to do to solve it

var locBase = DriveApp.getFileById("DOCUMENT_ID").getParents().next();

if (!masterFolder.hasNext()) {

            // If there isn't a principal folder, it creates it
            masterFolder= locBase.createFolder("individual_documents");

            // Creation of the first sub-folder (the course one)
            var courseFolder = masterFolder.next().createFolder(course);

            // The document is moved to the subfolder
            document.moveTo(courseFolder);

          } else {

            // If the principal folder its created it searches de course folder
            var courseFolder = masterFolder.next().getFoldersByName(course);

            if (!courseFolder.hasNext()) {

              // If the course folder doesn't exist, it creates it
              courseFolder = masterFolder.next().createFolder(course);

              // The sub-subfolder it's created (the class one) inside of the course folder
              var classFolder = courseFolder .createFolder(class);

              // The document is moved to the sub-subfolder
              document.moveTo(classFolder);

            } else {

              // If the subfolder exists, it searches the sub-subfolder inside of it
              var classFolder = courseFolder.next().getFoldersByName(class);

              if (!classFolder .hasNext()) {

                // If the sub-subfolder doesn't exist, it creates it
                var classFolder = courseFolder .next().createFolder(class);

                // The document is moved to the sub-subfolder
                document.moveTo(classFolder);

I expected to get in my Drive the main folder with the subfolders that contain de documents of each user, but it does not even manage to generate the documents that I need