0.3.7 add better error handling to avoid econnrest exception

http-server
David Kebler 2019-04-28 09:56:22 -07:00
parent feb6a93385
commit 16beda57ae
2 changed files with 21 additions and 8 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@uci/websocket", "name": "@uci/websocket",
"version": "0.3.6", "version": "0.3.7",
"description": "JSON packet host websocket server", "description": "JSON packet host websocket server",
"main": "src", "main": "src",
"scripts": { "scripts": {
@ -42,6 +42,7 @@
}, },
"dependencies": { "dependencies": {
"@uci-utils/logger": "0.0.14", "@uci-utils/logger": "0.0.14",
"await-to-js": "^2.1.1",
"better-try-catch": "^0.6.2", "better-try-catch": "^0.6.2",
"clone": "^2.1.2", "clone": "^2.1.2",
"death": "^1.1.0", "death": "^1.1.0",

View File

@ -1,5 +1,6 @@
import WebSocket from 'ws' import WebSocket from 'ws'
import btc from 'better-try-catch' import btc from 'better-try-catch'
import to from 'await-to-js'
import { promisify } from 'util' import { promisify } from 'util'
import _ON_DEATH from 'death' //this is intentionally ugly import _ON_DEATH from 'death' //this is intentionally ugly
import clone from 'clone' import clone from 'clone'
@ -70,6 +71,16 @@ class Socket extends WebSocket.Server {
let send = this._send.bind(socket) let send = this._send.bind(socket)
log.debug({method:'_listen', line:71, req: req, msg: 'new consumer connecting'}) log.debug({method:'_listen', line:71, req: req, msg: 'new consumer connecting'})
socket.address = req.remoteAddress socket.address = req.remoteAddress
socket.on('error', (err) => {
log.error({msg:'client connection error during listen',error:err})
})
socket.on('close', (msg) => {
log.warn({msg:'client connection closed during listen',error:msg})
})
socket.on('message', messageProcess.bind(this, socket)) socket.on('message', messageProcess.bind(this, socket))
async function messageProcess(client, strPacket) { async function messageProcess(client, strPacket) {
@ -133,14 +144,15 @@ class Socket extends WebSocket.Server {
// must have a consumer socket instance bound to call this function // must have a consumer socket instance bound to call this function
async _send(packet) { async _send(packet) {
return new Promise((resolve, reject) => { if (this.readyState !== 1) log.error({method:'_send', line:147, msg:`Connection not Ready, CODE:${this.readyState}`})
if (this.readyState !== 1) else {
reject(`Connection not Ready, CODE:${this.readyState}`)
let [err, message] = btc(JSON.stringify)(packet) let [err, message] = btc(JSON.stringify)(packet)
if (err) reject(`Could not JSON stringify: ${packet}`) if (err) log.error({method:'_send', line:147, msg:`WS Could not JSON stringify: ${packet}`})
this.send(message) else {
resolve('sent packet') try { this.send(message) }
}) catch(err) { log.error({method:'_send', line:153, msg:'error sending from ws server', error:err}) }
}
}
} }
} // end class } // end class