Node.js websocket unhandeled error events.js websocket.js - node.js

I am using express webserver with node.js and the standard websocket require('ws');
Now it happens sometimes when internet connection is lost, i think that is the main reason when this happen, i am getting then a error message and the script stops to run:
events.js:287
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27) Emitted 'error' event on WebSocket instance at:
at WebSocket.finalize (C:\Users\ABC\Desktop\Websocket\node_modules\ws\lib\WebSocket.js:182:41)
at TLSSocket.emit (events.js:310:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) { errno: 'ECONNRESET',
code: 'ECONNRESET', syscall: 'read' }
In the websocket client code i have also write a console.log or error events, see my code below:
ws.on('message', function incoming(data)
{
const obj = JSON.parse(data);
console.log("Stream: "+obj["k"].s+" "+obj["k"].i+" closeprice "+obj["k"].c+"\n");
});
ws.on('error', function(e){
console.log("stream error "+e);
});
the question is if i can do something to prevent this behavior? I normaly know that this problems happen when you dont console.log error events but for me it looks like i am doing that already. Maybe do i need to make changes in the ws module files?

Related

Error not being handled in chain of promises

I am fairly new to Node and am currently trying to tweak an existing project. Part of this uses the follow-redirects package to make HTTP(S) requests to fetch an image.
Occasionally my service crashes with the following trace:
events.js:174
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at Socket.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at ClientRequest.eventHandlers.(anonymous function) (/home/.../node_modules/follow-redirects/index.js:13:24)
at ClientRequest.emit (events.js:198:13)
at ClientRequest.EventEmitter.emit (domain.js:448:20)
at Socket.socketOnEnd (_http_client.js:426:9)
at Socket.emit (events.js:203:15)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:63:19)
I assume this means that I am dropping the error which comes back from the HTTP request.
Here is my function where I make the request:
function fetchRemote (imageUrl) {
let options = ...
return new Promise((resolve, reject) => {
https.get(options, resolve);
});
}
And it's called using a chain of promises.
fetchRemote(imageUrl)
.then(getResizeStream)
.then(storeImage)
.then(finished)
.catch(error);
function error (err) {
reject(new Error(`Failed: ${err.message}`));
};
Is there a logic pathway I'm missing, or should this properly catch the error? Or is the issue actually in the follow-redirects package?
Sockets are "event" emitter based and not promises. You need to handle errors on sockets by doing something along the lines of
socket.on('error',function(err){ /* handle error */});
// for you:
https
.get(options, resolve)
.on('error', err => {
reject(err);
});

UnhandledPromiseRejectionWarning WebSocket in NodeJs although implemented on error

I'm having issues with a webSocket connection (nodejs, ws). Now and then i see the following error message at the console and i don't know where it comes from. Seems like there is a problem with the internet connection or DNS server at the moment the error is raised. The application should be able to handle broken internet connection. At the moment the error is raised, the whole application stops.
The Error at the console:
(node:14656) UnhandledPromiseRejectionWarning: Error: Query timed out
at DNS._ontimeoutCheck (C:\Users\XYZ\Documents\nodedev\Server-DEV\node_modules\dns-socket\index.js:123:18)
at Timeout.ontimeoutCheck (C:\Users\XYZ\Documents\nodedev\Server-DEV\node_modules\dns-socket\index.js:53:10)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7)
(node:14656) UnhandledPromiseRejectionWarning: Error: Query timed out
Error: getaddrinfo ENOTFOUND connect.server.cloud
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
Emitted 'error' event on ServerCloud instance at:
at ServerCloud.<anonymous> (C:\Users\XYZ\Documents\nodedev\Server-
DEV\plugins\inbound\ks\ks.js:353:18)
at WebSocket.emit (events.js:223:5)
at ClientRequest.<anonymous> (C:\Users\XYZ\Documents\nodedev\Server-
DEV\node_modules\ws\lib\websocket.js:554:15)
at ClientRequest.emit (events.js:223:5)
at TLSSocket.socketErrorListener (_http_client.js:406:9)
at TLSSocket.emit (events.js:223:5)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:81:21) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'connect.server.cloud'
i have implemented the .on('error', (err) => { method in my code:
this._ws.on('error', function (error) {
this.connected = false;
this.emit('error', error);
this.LogAtMain('WebSocket Error: ' + error.message);
console.log('Error message: ' + error.message);
});
How can i catch this error unlike implementing the on(error) hook?
Somewhere in your code, you forgot to handle a promise rejection. That is why you are getting that error.
You can handle UnhandledPromiseRejectionWarning like this:
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason.stack);
// application specific logging, throwing an error, or other logic here
});

Cant find origin of Unhandled 'error' event ETIMEDOUT

I am building an application that is communicating with a local server through http requests, I decided to do a "real" test and it keeps throwing errors, but I cant track where the error is coming from, the stacktrace doesnt tell me where it originates from (in my app).
When I start my app it works for 20-30 seconds, it manages to get/send data to that local webserver, but after 20-30 seconds I get the following error:
events.js:287
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 192.168.55.213:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
Emitted 'error' event on ClientRequest instance at:
at Socket.socketErrorListener (_http_client.js:426:9)
at Socket.emit (events.js:310:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: '192.168.55.213',
port: 80
}
I have tried all my http requests in a try/catch block and log the errors to try and pinpoint where it originates from but nothing, the try/catches dont work, because the error is still being thrown, so it is not from within my http requests and I cant figure out the origin of the error. My requests look something like this:
async RequestFunction(requesturl) {
return new Promise((resolve, reject) => {
try {
http.get(requesturl, (resp) => {
let data = "";
resp.on('data', (chunk) => data += chunk)
resolve(data)
});
} catch (error) {
console.log(`${requesturl}+${error.code}`);
}
}
}
But the catch never gets triggered. I am guessing that mostly what I am asking for is how to track where the error is originating from?
I have also tried wrapping my Request function in every place where I am calling and awaiting it with a try/catch block, same thing.

I can not handle error event in net.createServer

proxy multiple proxies by net.createServer
here is my all code
var proxies='127.0.0.1:4444,127.0.0.1:4443,127.0.0.1:4442'.split(',');
var net = require('net');
function randgetir(){
d=proxies[Math.floor(Math.random() * proxies.length)].split(':');
return [d[0],d[1]];
}
var cre=net.createServer(function(from) {
var prgs=randgetir();
var to = net.createConnection({host: prgs[0],
port: prgs[1]
}).on('error', function(error) {
});
from.pipe(to);
to.pipe(from);
}).on('error', function(error) {
});
cre.listen("56666");
when i run the code sometimes i get
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:162:27)
Emitted 'error' event at:
at errorOrDestroy (internal/streams/destroy.js:98:12)
at Socket.onerror (_stream_readable.js:720:7)
at Socket.emit (events.js:197:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at processTicksAndRejections (internal/process/next_tick.js:76:17)
error and my app just crash and exit but as you see i handle all the error events,
what may i be doing wrong?
The problem is that there is no error handler attached to the incoming message stream. You could attach a handler like this:
from.on('error', function(e){ ...}))
.pipe(to);
Maybe check out this post on stackoverflow for more information regarding error handling with streams/pipes: Error handling with node.js streams

Sequelize Error with query sending Error: read ECONNRESET

PostgreSQL 9.6.2 I send query from node.js / express.js application.
The sequelize provide the doc how to make the query, this example findAll.
I try to make same example.
console.log('user id: ', req.decoded);
db.orders.findAll({where: {userId: req.decoded.id}})
.then(function (orders) {
console.log('orders from db: ', orders);
})
.catch(function (err) {
console.log('orders request error from db: ', err);
});
console.log('end of function');
Console log:
user id: { id: 2 }
end of function
orders request error from db: { SequelizeConnectionError: read ECONNRESET
at D:\NodeJSProjects\ParkingHouse\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:110:20
at Connection.<anonymous> (D:\NodeJSProjects\ParkingHouse\node_modules\pg\lib\client.js:186:5)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Socket.<anonymous> (D:\NodeJSProjects\ParkingHouse\node_modules\pg\lib\connection.js:86:10)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1278:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'SequelizeConnectionError',
message: 'read ECONNRESET',
parent:
{ Error: read ECONNRESET
at exports._errnoException (util.js:1022:11)
at TCP.onread (net.js:569:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' },
original:
{ Error: read ECONNRESET
at exports._errnoException (util.js:1022:11)
at TCP.onread (net.js:569:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' } }
After some time the request is repeated and then I get the data from db.
I found the similar topic Node js ECONNRESET but I don't found answer.
Why db close the connection? And how to repair it.
The problem was in antivirus F-Secure, change it and all works.
Some problem:
https://community.f-secure.com/t5/Business/DeepGuard-seems-to-cause/td-p/88447
You are loosing you connection. Probably you are not calling next() in your framework. Or do not close transaction.
This structure does not make sense:
.then(function (foundUser) {
return foundUser;
}).catch(function (err) {
//get here the exception
return err;
});
Just remove it. Then rewrite your controller to something like
const user = await authorize(req);
if (!user) {
res.status(401).send('Authorization required');
return next();
}
res.status(200).send('All ok');
next();
On error your framework should serve 500 automatically for you. If you want to handle it manually use try { await Promise } catch (err) { }
If you use something that does not support await/async yet, than take a look at http://koajs.com/
I had similar Error today
{
error: {
Error: write ECONNRESET at WriteWrap.afterWrite (net.js:788:14) errno: 'ECONNRESET',
code: 'ECONNRESET', syscall: 'write'
}
}
You need to set the database maximum pool or avoid sending multiple at the same time.
Here there is a github thread that may help you.

Resources