Node Server ECONNRESET error occurs after running a sql request - node.js

I'm making a node server using socket.js and a MYSQL DB,
socket.on("signUp", (userSignUp) => {
console.log(userSignUp);
con.connect(function() {
con.query("SELECT COUNT(*) AS count FROM users WHERE username = '" + userSignUp.username + "'", function (err, result, fields) {
console.log(result[0].count);
if (result[0].count >= 1) {
socket.emit("signUpError", 'user-allready-exists');
return;
}
});
});
});
When I run this function, it successfully gets the data from the db however after aproximatly 30 seconds, it gives me this error>>>
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (D:\Projects\server\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (node:events:513:28)
at Protocol._delegateError (D:\Projects\server\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError (D:\Projects\server\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError (D:\Projects\server\node_modules\mysql\lib\Connection.js:418:18)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
I have had a good look around, but i can't seem to find what is causing this issue. Any help would be greatly appreciated.

Related

Node.js websocket unhandeled error events.js websocket.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?

Node JS trying to download a number of images. Stream seems to keep being closed

I'm looping through quite a lot of images to download from a website using this function:
const fileGet = (url, path, callback) => {
request.head(url, (err, res, body) => {
request(url)
.pipe(fs.createWriteStream(path))
})
.on('error', function(err, res) {
console.log(err + res)
})
}
It seems to get so far and then the stream seems to be closed. I've been doing some googling and people mention it could be trying to resolve too many dns lookups in a given time.
This is the error I'm getting:
node:events:371
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND www.domain.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)
Emitted 'error' event on Request instance at:
at Request.onerror (node:internal/streams/legacy:62:12)
at Request.emit (node:events:394:28)
at Request.onRequestError (C:\Scraper\node_modules\request\request.js:877:8)
at ClientRequest.emit (node:events:394:28)
at TLSSocket.socketErrorListener (node:_http_client:447:9)
at TLSSocket.emit (node:events:394:28)
at emitErrorNT (node:internal/streams/destroy:193:8)
at emitErrorCloseNT (node:internal/streams/destroy:158:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'www.domain.com'
}
I've tried hard coding the IP/Host name in my Hosts file, and tried putting a pause in the requests, same problem. I've also upgraded to the last version of Node (16.4.0)
Still the same.
There is a lot of debate about this issue online. Has it even been resolved?
Thanks.
If anybody is interested, it was a DNS lookup issue, and sorted it by using DNS Cache.
Just wrapper my whole download process with an initial look up, and the rest ran like a dream.

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
});

Recaptcha Handling Throwing Exception Inside Promise with catch

Does anybody know how to handle the error from below properly? Obviously, I am using a 3rd party library that performs an internal HTTP poll to a remote API, sometimes, it throws a connection refusal error and crashes the whole NodeJS process.
return new Promise((resolve, reject) => {
page.getRecaptchaSolutions(captchas).then(({ solutions, solErrors }) => {
if (solErrors)
reject(solErrors);
resolve(solutions)
})
.catch(error => {
reject(new Error(error))
})
})
Error: getaddrinfo EAI_AGAIN 2captcha.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
Emitted 'error' event on ClientRequest instance at:
at Socket.socketErrorListener (_http_client.js:406:9)
at Socket.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: 'EAI_AGAIN',
code: 'EAI_AGAIN',
syscall: 'getaddrinfo',
hostname: '2captcha.com'
}

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