Fixing loop bug in error case