0.3.7 add better error handling to avoid econnrest exception
parent
feb6a93385
commit
16beda57ae
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@uci/websocket",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"description": "JSON packet host websocket server",
|
||||
"main": "src",
|
||||
"scripts": {
|
||||
|
@ -42,6 +42,7 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"@uci-utils/logger": "0.0.14",
|
||||
"await-to-js": "^2.1.1",
|
||||
"better-try-catch": "^0.6.2",
|
||||
"clone": "^2.1.2",
|
||||
"death": "^1.1.0",
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import WebSocket from 'ws'
|
||||
import btc from 'better-try-catch'
|
||||
import to from 'await-to-js'
|
||||
import { promisify } from 'util'
|
||||
import _ON_DEATH from 'death' //this is intentionally ugly
|
||||
import clone from 'clone'
|
||||
|
@ -70,6 +71,16 @@ class Socket extends WebSocket.Server {
|
|||
let send = this._send.bind(socket)
|
||||
log.debug({method:'_listen', line:71, req: req, msg: 'new consumer connecting'})
|
||||
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))
|
||||
|
||||
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
|
||||
async _send(packet) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.readyState !== 1)
|
||||
reject(`Connection not Ready, CODE:${this.readyState}`)
|
||||
if (this.readyState !== 1) log.error({method:'_send', line:147, msg:`Connection not Ready, CODE:${this.readyState}`})
|
||||
else {
|
||||
let [err, message] = btc(JSON.stringify)(packet)
|
||||
if (err) reject(`Could not JSON stringify: ${packet}`)
|
||||
this.send(message)
|
||||
resolve('sent packet')
|
||||
})
|
||||
if (err) log.error({method:'_send', line:147, msg:`WS Could not JSON stringify: ${packet}`})
|
||||
else {
|
||||
try { this.send(message) }
|
||||
catch(err) { log.error({method:'_send', line:153, msg:'error sending from ws server', error:err}) }
|
||||
}
|
||||
}
|
||||
}
|
||||
} // end class
|
||||
|
||||
|
|
Loading…
Reference in New Issue