Fix file handle leak in the error path