Cleanup connection properly on error