Search code examples
pythonpython-3.xdjangoexceptiontry-catch

For loop catch Exception before called function do it's job


I got a code that connects to Binance api/url and sometime has ConnectionError.

My code is like:

def initial_connect(self):

        try:

            client = Spot(key=self.api_key, secret=self.secret_key,    base_url='https://api4.binance.com')
            

        
        except:

            client = Spot(key=self.api_key, secret=self.secret_key, base_url='https://api2.binance.com')
            

        finally:

            return client

And I use this function in another file in a for loop with try block, to log the errors:

for trade in trades:

        try:
           initial_connect()
        
        except Exception as e:
            error_log(str(e))

So in this case when first connections fails, doesn't go to function (initial_connect) except block and try other url, then in for loop except block get the Exception and write the error log.

The question is, How can I edit my code so after a connection failure checks another one, if second fails the for loop try block catch the exception?

I just tried with try block in serveral orders and the result was the same.


Solution

  • You could place your urls into a list which you iterate over. In the loop you try to connect and return the client. If all urls fail, raise a new Exception.

    def initial_connect(self):
        base_urls = ['https://api4.binance.com', 'https://api2.binance.com']
        for base_url in base_urls:
            try:
                client = Spot(key=self.api_key, secret=self.secret_key, base_url=base_url)
                return client
            except Exception as err:
                continue
    
        raise Exception('All base urls exhausted')