Refactor the error handling logic around connect()