From cd8f965376f86102940bc43aa9ec3a818d9104f9 Mon Sep 17 00:00:00 2001 From: maciejhirsz Date: Fri, 27 Jul 2018 12:51:15 +0200 Subject: [PATCH] Nicer error handling on sockets --- packages/backend/src/Feed.ts | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/packages/backend/src/Feed.ts b/packages/backend/src/Feed.ts index d6a02c2..2c1069f 100644 --- a/packages/backend/src/Feed.ts +++ b/packages/backend/src/Feed.ts @@ -2,7 +2,7 @@ import * as WebSocket from 'ws'; import * as EventEmitter from 'events'; import Node from './Node'; import Chain from './Chain'; -import { VERSION, noop, timestamp, Maybe, FeedMessage, Types, idGenerator } from '@dotstats/common'; +import { VERSION, timestamp, Maybe, FeedMessage, Types, idGenerator } from '@dotstats/common'; import { Location } from './location'; const nextId = idGenerator(); @@ -120,13 +120,7 @@ export default class Feed { } public sendData(data: FeedMessage.Data) { - try { - this.socket.send(data); - } catch (err) { - console.error('Failed to send data to a Feed', err); - - this.disconnect(); - } + this.socket.send(data, this.handleError); } public sendMessage(message: FeedMessage.Message) { @@ -146,19 +140,13 @@ export default class Feed { } this.waitingForPong = true; - try { - this.socket.ping(noop); - } catch (err) { - console.error('Failed to send ping to Feed', err); - - this.disconnect(); - } + this.socket.ping(this.handleError); } private sendMessages = () => { const data = FeedMessage.serialize(this.messages); this.messages = []; - this.socket.send(data); + this.socket.send(data, this.handleError); } private handleCommand(cmd: string) { @@ -187,6 +175,14 @@ export default class Feed { } } + private handleError = (err: Maybe) => { + if (err) { + console.error('Error when sending data to the socket', err); + + this.disconnect(); + } + } + private disconnect() { this.socket.removeAllListeners(); this.socket.terminate();