Nicer error handling on sockets

This commit is contained in:
maciejhirsz
2018-07-27 12:51:15 +02:00
parent 20d8b21adc
commit cd8f965376
+12 -16
View File
@@ -2,7 +2,7 @@ import * as WebSocket from 'ws';
import * as EventEmitter from 'events'; import * as EventEmitter from 'events';
import Node from './Node'; import Node from './Node';
import Chain from './Chain'; 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'; import { Location } from './location';
const nextId = idGenerator<Types.FeedId>(); const nextId = idGenerator<Types.FeedId>();
@@ -120,13 +120,7 @@ export default class Feed {
} }
public sendData(data: FeedMessage.Data) { public sendData(data: FeedMessage.Data) {
try { this.socket.send(data, this.handleError);
this.socket.send(data);
} catch (err) {
console.error('Failed to send data to a Feed', err);
this.disconnect();
}
} }
public sendMessage(message: FeedMessage.Message) { public sendMessage(message: FeedMessage.Message) {
@@ -146,19 +140,13 @@ export default class Feed {
} }
this.waitingForPong = true; this.waitingForPong = true;
try { this.socket.ping(this.handleError);
this.socket.ping(noop);
} catch (err) {
console.error('Failed to send ping to Feed', err);
this.disconnect();
}
} }
private sendMessages = () => { private sendMessages = () => {
const data = FeedMessage.serialize(this.messages); const data = FeedMessage.serialize(this.messages);
this.messages = []; this.messages = [];
this.socket.send(data); this.socket.send(data, this.handleError);
} }
private handleCommand(cmd: string) { private handleCommand(cmd: string) {
@@ -187,6 +175,14 @@ export default class Feed {
} }
} }
private handleError = (err: Maybe<Error>) => {
if (err) {
console.error('Error when sending data to the socket', err);
this.disconnect();
}
}
private disconnect() { private disconnect() {
this.socket.removeAllListeners(); this.socket.removeAllListeners();
this.socket.terminate(); this.socket.terminate();