This logic (connecting and handling error) is duplicated elsewhere in the function, think, you could wrap it up into an internal function? Also, is there anyplace else that should have this behavior as well? Like, any other functions that might want to be able to reconnect on error?