Catching exception related to websocket

Rekha
Running kite ticker, when http connection is lost, I get a log error message:
2022-09-08 22:07:18,569 - kiteconnect.ticker - Thread-1 (run) - ERROR - Connection error: 1006 - connection was closed uncleanly (None)

How can I catch this error and handle it? I am clueless about it. Thanks in advance

  • Rekha
    here is the complete code:
    from kiteconnect import KiteConnect
    from kiteconnect import KiteTicker
    import time
    import logging

    logging.basicConfig(format='%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s',
    level=logging.INFO, handlers=[logging.StreamHandler()])

    access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    api_key = 'xxxxxxxxxxxxx'
    kite = KiteConnect(api_key)
    kite.set_access_token(access_token)

    my_ticks = []


    def on_ticks(ws, ticks):
    global my_ticks
    my_ticks.extend(ticks) # adding multiple elements to the end of the list


    tokens = [2976257]


    def on_connect(ws, response):
    ws.subscribe(tokens)
    ws.set_mode(ws.MODE_FULL, tokens)


    def on_close(ws, code, reason):
    pass
    # On connection close stop the event loop.
    # Reconnection will not happen after executing `ws.stop()`
    # ws.stop()


    kws = KiteTicker(api_key, access_token)
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    kws.connect(threaded=True)

    while True:
    if my_ticks:
    print(my_ticks[-1])
    time.sleep(5)
  • Rekha
    where shall I put try-catch to catch the error 1006 as mentioned above?
  • rakeshr
    Running kite ticker, when http connection is lost, I get a log error message:
    where shall I put try-catch to catch the error 1006 as mentioned above?
    You don't need to handle this here, as ticker auto reconnects by default. Just make sure not to have ws.stop() i.e force stop the ticker anywhere undesired. Multi-line comment here explains about auto-reconnect mechanism in more detail.
  • Rekha
    so you mean to say that no exception will be generated and I should let the auto-reconnect feature take care of the situation? should I handle the error log by adding filter to the logger?
  • rakeshr
    so you mean to say that no exception will be generated
    An exception log will be generated, but the connection will not be closed.
    I should let the auto-reconnect feature take care of the situation?
    Yes. A good practice here is to not stop/close the ticker connection for minor/expected exceptions, which don't affect the main outcome.
    should I handle the error log by adding filter to the logger?
    Log messages are meant to track events during the runtime. So, filtering or not dependents on your use case.
  • Rekha
    I see only log error messages, but no exception. I guess exception is raised only when there are more serious issues in network. Had there been an exception, I would have caught it and run some code.
Sign In or Register to comment.