well, at first there is missing else case, at least log warning.

At second. I think it will be much readable without while cycle, just use recursion instead of next and it will work more intuitive