fix: close resources on error paths (#7940)