Ensure cmdwriter closes on error