Skip to content

Commit

Permalink
feat(v4.0.0-beta.5): BREAKING CHANGE: rename "error" event to "except…
Browse files Browse the repository at this point in the history
…ion" to avoid unhandled exceptions
  • Loading branch information
tiagosiebler committed Feb 6, 2025
1 parent a8f8d6b commit 57b1a72
Show file tree
Hide file tree
Showing 10 changed files with 42 additions and 45 deletions.
2 changes: 1 addition & 1 deletion examples/demo-trading.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function setWsClientEventListeners(
websocketClient.on('reconnected', (data) => {
console.log(new Date(), accountRef, 'ws has reconnected ', data?.wsKey);
});
websocketClient.on('error', (data) => {
websocketClient.on('exception', (data) => {
console.error(new Date(), accountRef, 'ws exception: ', data);
});
});
Expand Down
2 changes: 1 addition & 1 deletion examples/fasterHmacSign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ function setWsClientEventListeners(
websocketClient.on('reconnected', (data) => {
console.log(new Date(), accountRef, 'ws has reconnected ', data?.wsKey);
});
websocketClient.on('error', (data) => {
websocketClient.on('exception', (data) => {
console.error(new Date(), accountRef, 'ws exception: ', data);
});
});
Expand Down
4 changes: 2 additions & 2 deletions examples/ws-api-promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ wsClient.on('reconnected', (data) => {
wsClient.on('authenticated', (data) => {
console.log('ws has authenticated ', data?.wsKey);
});
wsClient.on('error', (data) => {
console.error('ws error: ', data);
wsClient.on('exception', (data) => {
console.error('ws exception: ', data);
});

async function main() {
Expand Down
15 changes: 6 additions & 9 deletions examples/ws-public-v5.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,8 @@ const logger = {
* - Heartbeats/ping/pong/reconnects are all handled automatically.
* If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you.
*/
const wsClient = new WebsocketClient(
{
// demoTrading: true,
},
logger,
);

const wsClient = new WebsocketClient();

wsClient.on('update', (data) => {
console.log('raw message received ', JSON.stringify(data));
Expand All @@ -40,9 +36,10 @@ wsClient.on('reconnect', ({ wsKey }) => {
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
// wsClient.on('error', (data) => {
// console.error('ws exception: ', data);
// });

wsClient.on('exception', (data) => {
console.error('ws exception: ', data);
});

/**
* For public V5 topics, use the subscribeV5 method and include the API category this topic is for.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bybit-api",
"version": "4.0.0-beta.4",
"version": "4.0.0-beta.5",
"description": "Complete & robust Node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & strong end to end tests.",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
30 changes: 13 additions & 17 deletions src/util/BaseWSClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
} from './websockets';
import { WsOperation } from '../types/websockets/ws-api';

type UseTheExceptionEventInstead = never;

interface WSClientEventMap<WsKey extends string> {
/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
open: (evt: { wsKey: WsKey; event: any }) => void;
Expand All @@ -39,10 +41,10 @@ interface WSClientEventMap<WsKey extends string> {
/** Received data for topic */
update: (response: any & { wsKey: WsKey }) => void;
/**
* Exception from ws client OR custom listeners (e.g. if you throw inside your event handler)
* @deprecated Use 'exception' instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection.
* See for more information: https://github.com/tiagosiebler/bybit-api/issues/413
* @deprecated Use the 'exception' event instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection.
*/
error: (response: any & { wsKey: WsKey; isWSAPIResponse?: boolean }) => void;
error: UseTheExceptionEventInstead;
/**
* Exception from ws client OR custom listeners (e.g. if you throw inside your event handler)
*/
Expand All @@ -57,12 +59,6 @@ interface WSClientEventMap<WsKey extends string> {
}) => void;
}

export interface EmittableEvent<TEvent = any> {
eventType: 'response' | 'update' | 'error' | 'authenticated';
event: TEvent;
isWSAPIResponse?: boolean;
}

// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837
export interface BaseWebsocketClient<
TWSKey extends string,
Expand All @@ -80,6 +76,12 @@ export interface BaseWebsocketClient<
): boolean;
}

export interface EmittableEvent<TEvent = any> {
eventType: 'response' | 'update' | 'exception' | 'authenticated';
event: TEvent;
isWSAPIResponse?: boolean;
}

/**
* A midflight WS request event (e.g. subscribe to these topics).
*
Expand Down Expand Up @@ -167,12 +169,6 @@ export abstract class BaseWebsocketClient<
authPrivateRequests: false,
...options,
};

// add default error handling so this doesn't crash node (if the user didn't set a handler)
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars, no-unused-vars
this.on('error', (e) => {
// console.log('basewserr: ', e);
});
}

/**
Expand Down Expand Up @@ -593,7 +589,7 @@ export abstract class BaseWebsocketClient<
if (!error.message) {
this.logger.error(`${context} due to unexpected error: `, error);
this.emit('response', { ...error, wsKey });
this.emit('error', { ...error, wsKey });
this.emit('exception', { ...error, wsKey });
return;
}

Expand Down Expand Up @@ -628,7 +624,7 @@ export abstract class BaseWebsocketClient<
this.logger.error(`parseWsError(${context}, ${error}, ${wsKey}) `, error);

this.emit('response', { ...error, wsKey });
this.emit('error', { ...error, wsKey });
this.emit('exception', { ...error, wsKey });
}

/** Get a signature, build the auth request and send it */
Expand Down
8 changes: 4 additions & 4 deletions src/websocket-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export class WebsocketClient extends BaseWebsocketClient<
perWsKeyTopics[derivedWsKey] = [];
}

perWsKeyTopics[derivedWsKey].push(wsRequest);
perWsKeyTopics[derivedWsKey]!.push(wsRequest);
}

const promises: Promise<unknown>[] = [];
Expand Down Expand Up @@ -755,7 +755,7 @@ export class WebsocketClient extends BaseWebsocketClient<
}

results.push({
eventType: 'error',
eventType: 'exception',
event: parsed,
isWSAPIResponse: true,
});
Expand Down Expand Up @@ -804,7 +804,7 @@ export class WebsocketClient extends BaseWebsocketClient<
// Failed request
if (parsed.success === false) {
results.push({
eventType: 'error',
eventType: 'exception',
event: parsed,
});
return results;
Expand Down Expand Up @@ -851,7 +851,7 @@ export class WebsocketClient extends BaseWebsocketClient<
exception: e,
eventData: event.data,
},
eventType: 'error',
eventType: 'exception',
});

this.logger.error('Failed to parse event data due to exception: ', {
Expand Down
10 changes: 7 additions & 3 deletions test/v5/public.ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@ describe.skip('Public V5 Websocket client', () => {
describe('Topics subscription confirmation', () => {
it('can subscribeV5 to LINEAR with valid topic', async () => {
await expect(
api.subscribeV5(`publicTrade.${linearSymbol}`, linearCategory),
).resolves.toBeUndefined();
Promise.allSettled(
api.subscribeV5(`publicTrade.${linearSymbol}`, linearCategory),
),
).resolves.toStrictEqual([]);
});

it('cannot subscribeV5 to LINEAR with valid topic', async () => {
try {
await api.subscribeV5(`publicTrade.${linearSymbol}X`, linearCategory);
await Promise.allSettled(
api.subscribeV5(`publicTrade.${linearSymbol}X`, linearCategory),
);
} catch (e) {
expect(e).toBeDefined();
expect(e).toMatch(`(publicTrade.${linearSymbol}X) failed to subscribe`);
Expand Down
10 changes: 5 additions & 5 deletions test/ws.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function waitForSocketEvent(
}

wsClient.on(event, (e) => resolver(e));
wsClient.on('error', (e) => rejector(e));
wsClient.on('exception', (e) => rejector(e));

// if (event !== 'close') {
// wsClient.on('close', (event) => {
Expand All @@ -78,21 +78,21 @@ export function waitForSocketEvent(

export function listenToSocketEvents(wsClient: WebsocketClient) {
const retVal: Record<
'update' | 'open' | 'response' | 'close' | 'error',
'update' | 'open' | 'response' | 'close' | 'exception',
typeof jest.fn
> = {
open: jest.fn(),
response: jest.fn(),
update: jest.fn(),
close: jest.fn(),
error: jest.fn(),
exception: jest.fn(),
};

wsClient.on('open', retVal.open);
wsClient.on('response', retVal.response);
wsClient.on('update', retVal.update);
wsClient.on('close', retVal.close);
wsClient.on('error', retVal.error);
wsClient.on('exception', retVal.exception);

return {
...retVal,
Expand All @@ -101,7 +101,7 @@ export function listenToSocketEvents(wsClient: WebsocketClient) {
wsClient.removeListener('response', retVal.response);
wsClient.removeListener('update', retVal.update);
wsClient.removeListener('close', retVal.close);
wsClient.removeListener('error', retVal.error);
wsClient.removeListener('exception', retVal.exception);
},
};
}
Expand Down

0 comments on commit 57b1a72

Please sign in to comment.