Sometimes WebSocket message event returns undefined value

I call the function below:

const getOpenOrders = () => {
  // ws_api ??= new WebSocket(binance.WEBSOCKET_API);

  const params = {
    apiKey: binance.API_KEY,
  const searchParams = new URLSearchParams({ ...params });
  const signature = binance.signature(searchParams.toString());
  searchParams.append("signature", signature);

    id: "openOrders_status",
    method: "openOrders.status",
    params: Object.fromEntries(searchParams)

in the open event.

ws_api.on("open", () => {

Then in the message event I try to do this:

ws_api.on("message", data => {
  data = JSON.parse(data);

  switch ( {
    case 'openOrders_status':
      openOrders = { };
      openOrders.hasPrice = price => !!openOrders.result.find(openOrder => parseFloat(openOrder.price) === price);

Then I call getOpenOrders() when executionReport is executed.

This code seems to work well for hours but sometimes I get this error:

TypeError: Cannot read properties of undefined (reading ‘find’) at openOrders.hasPrice

It seems that openOrders variable is undefined but this is impossible because I can read value. What’s wrong?
I thing that message event should return always a defined value.

The error you’re encountering, TypeError: Cannot read properties of undefined (reading 'find') at openOrders.hasPrice, indicates that openOrders.result is undefined when you try to access its find method.

To address this issue, you should ensure that openOrders.result exists before attempting to use the find method.

I know that I should ensure that openOrders.result exists but I think that it should always exists when returned by the message event. There could be any case when it is undefined?

Hi @gputignano, this is a programming question which you need to debug locally to check why it’s undefined by printing the msg content directly.

1 Like