Servus
Servus

Reputation: 517

Python not throwing errors or exceptions, websocket on_message

Why is python not throwing errors or exceptions when I pass too many arguments to f()? Obviously, f() is not executed because of the error. I am using VS-Code and python 3.8. (If you want to replicate, you have to install the websocket_client package)

import websocket
import json

connection = "wss://ws-feed.pro.coinbase.com"
subscription = json.dumps({
    "type": "subscribe",
    "channels": [
        {
            "name": "level2",
            "product_ids": ["BTC-USD"]
        }
    ]
})

def f(msg):
    print(msg)

def ws_message(ws, message):
    f("hi",True) #<--should throw a too many arguments error/exception
    

def ws_open(ws):
    ws.send(subscription)

def ws_thread(*args):
    ws = websocket.WebSocketApp(
        connection,  on_message=ws_message, on_open=ws_open)
    ws.run_forever()

ws_thread()

Upvotes: 1

Views: 1591

Answers (2)

Peter Lu
Peter Lu

Reputation: 1

I tried to run your above code and it worked when I inserted the debugging code listed in the documentation: https://websockets.readthedocs.io/en/2.6/. This code below will throw the appropriate errors:

import websocket
import json
import logging
logger = logging.getLogger('websocket')
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
# websocket._logging._logger.level = -99

connection = "wss://ws-feed.pro.coinbase.com"
subscription = json.dumps({
    "type": "subscribe",
    "channels": [
        {
            "name": "level2",
            "product_ids": ["BTC-USD"]
        }
    ]
})

def f(msg):
    print(msg)

def ws_message(ws, message):
    f("hi",True) #<--should throw a too many arguments error/exception
    

def ws_open(ws):
    ws.send(subscription)

def ws_thread(*args):
    ws = websocket.WebSocketApp(
        connection,  on_message=ws_message, on_open=ws_open)
    ws.run_forever()

ws_thread()

Upvotes: 0

Gabriel Milan
Gabriel Milan

Reputation: 723

This is due to a failsafe mechanism implemented here. If you'd like to track your exceptions, you should set a proper level to the logger. For that, do:

import websocket
websocket._logging._logger.level = -99 # This will enable all levels of logging

# Rest of your code goes here

That way, after running your code, you would see:

  File "blablabla/.local/lib/python3.7/site-packages/websocket/_app.py", line 346, in _callback
    callback(self, *args)
  File "blablabla/test/test.py", line 22, in ws_message
    f("hi", True) #<--should throw a too many arguments error/exception

Your code would still be running, but you would be able to catch exceptions

Upvotes: 1

Related Questions