Refactor tryConnect function.