I am getting below error every day if I left the software for more than 2 to 4 hours.
{
code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
fatal: false
}
{ Error: Cannot enqueue Handshake after fatal error.
at Protocol._validateEnqueue (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:200:16)
at Protocol._enqueue (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:138:13)
at Protocol.handshake (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:118:18)
at connectMysql (/home/zubizi/retech_node_beta/index.js:38:14)
at Connection.<anonymous> (/home/zubizi/retech_node_beta/index.js:52:13)
at Connection.emit (events.js:182:13)
at Connection._handleProtocolError (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:425:8)
at Protocol.emit (events.js:182:13)
at Protocol._delegateError (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:390:10)
at Protocol.end (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:116:8)
at Socket.<anonymous> (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:97:28)
at Socket.<anonymous> (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:502:10)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at args.(anonymous function) (/home/zubizi/.nvm/versions/node/v11.2.0/lib/node_modules/pm2/node_modules/event-loop-inspector/index.js:138:29)
at process.internalTickCallback (internal/process/next_tick.js:72:19) code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }
I tried below code to keep the connection alive. But the result is still the same.
// keep connection alive
setInterval(function () {
var datetime = moment.format('DD-MM-YYYY');
conn.query('SELECT 1');
console.log('Keep alive the connection. ' + datetime);
}, 10000);
I use this method to connect with MySQL
const conn = mysql.createConnection(config);
conn.connect(function (err) {
if (err) {
console.error(err);
// process.exit(1);
} else {
console.log(`DB Host: ${config.host}, DB: ${config.database}`);
console.log("Connected!");
}
});
and if any user logs in I change the database like this:
conn.changeUser({
database: req.session.dbname
}, function (err) {
if (err) {
console.log(err);
} else {
next();
}
});
Is the process is wrong or there is a solution for this????
Related
I need help with socket.io-redis-adapter as their document on Client Error Handling seems to be gone.
I do not know how this error with Redis occur, has it got to do with Redis pub/sub? My redis server is in working error through out.
I've searched through forums and github. I've followed the recommended actions as follows. However, I'm still not able to catch the errors below, and it's causing my app to crash. My redis servers are all well and not disconnected at that time as I have other services using same server.
Can anyone provide me with some directions?
"#socket.io/redis-adapter": "^7.0.0",
"#socket.io/redis-emitter": "^4.1.0",
Catching error for both sub and pub client - Done ✅
// I'm using ioredis and I believe ioredis will auto handle reconnection?
pubClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON pubClient %O`, err)
})
subClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON subClient %O`, err)
})
Catch error on adapter - Done ✅
// But i think this is not working to catch errors ❌❌❌
io.of('/').adapter.on('error', function(error){
debug('error: ', error);
});
Ping to keep connection alive - Done ✅
setInterval(() => {
// emitter.of('/user').emit("time", new Date);
io.of('/user').emit("time", new Date())
}, 300000);
I've also tried using both node-redis and ioredis and both end up with same error below Done ✅
Manage to catch this with redis on error event ✅
socket REDIS ADAPTOR DISCONNECTED ON pubClient Error: read ECONNRESET
socket at TCP.onStreamRead (internal/stream_base_commons.js:209:20) {
socket errno: -54,
socket code: 'ECONNRESET',
socket syscall: 'read'
socket } +5h
socket error: Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
} +0ms
// Unable to catch this event ❌❌❌
// I think this causes my app to crash
events.js:292
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on RedisAdapter instance at:
at Redis.onError (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/#socket.io/redis-adapter/dist/index.js:61:22)
at Redis.emit (events.js:327:22)
at Redis.EventEmitter.emit (domain.js:486:12)
at Redis.silentEmit (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/ioredis/built/redis/index.js:544:26)
at Socket.<anonymous> (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/ioredis/built/redis/event_handler.js:190:14)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:327:22)
at Socket.EventEmitter.emit (domain.js:486:12)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
}
This is snippet of how my server is created;
....server declaration codes
const { createAdapter } = require("#socket.io/redis-adapter");
const Redis = require("ioredis");
const pubClient = new Redis({
host: process.env.SOCKET_IO_REDIS_HOST,
port: process.env.SOCKET_IO_REDIS_PORT,
username: process.env.SOCKET_IO_REDIS_USER,
password: process.env.SOCKET_IO_REDIS_PASSWORD,
db: process.env.SOCKET_IO_REDIS_DB,
})
const subClient = pubClient.duplicate();
const adapter = createAdapter(pubClient, subClient)
io.adapter(adapter)
pubClient.on("ready", () => {
debug(`REDIS ADAPTOR CONNECTED`)
})
pubClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON pubClient %O`, err)
})
subClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON subClient %O`, err)
})
pubClient.on("end", (err) => {
debug(`REDIS ADAPTOR ENDED %O`, err)
})
setInterval(() => {
// emitter.of('/user').emit("time", new Date);
io.of('/user').emit("time", new Date())
}, 300000);
io.of('/').adapter.on('error', function(error){
debug('error: ', error);
});
The class:
const mysql = require('mysql');
module.exports = function () {
this.connection = mysql.createConnection({
host : 'localhost',
user : 'USER',
password : 'PASSWORD',
database : 'DATABASE',
multipleStatements: true
});
this.query = (sql, args) => {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err );
resolve( rows );
});
});
};
this.close = () => {
return async () => {
try {
this.connection.end(err => {
if (err) throw err;
return;
});
} catch(e) {
return e;
}
}
};
};
In index i call it like this:
const Database = require('./server/modules/mysql'),
connection = new Database();
The problem:
Overnight mysql crashes:
[nodemon] starting `node index.js`
listening on port 420
events.js:292
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:315:20)
at Protocol._delegateError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:116:8)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
[... lines matching original stack trace ...]
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
[nodemon] app crashed - waiting for file changes before starting...
I'm using Nodemon and a simple restart to the application solves the issue until the next morning (or next long period of not coding.)
I'm not really using close() anywhere or after anything since in the docs it says it's not needed, just query().
but clearly i get a timeout somewhere somehow, like i should deal with the opening and closing of connection.
Do i need to close connections after making queries in my app?
Is there a way to set the timeout limit or dealing with him?
Am i just setting it up wrong or using wrong/outdated tool?
Thanks.
I have a reddit bot written in Nodejs with Snoowrap and Snoostorm and deployed to Heroku.
My logs keeps churning this error out:
2020-03-13T06:02:53.784219+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: RequestError: Error: ESOCKETTIMEDOUT
2020-03-13T06:02:53.784229+00:00 app[web.1]: at new RequestError (/app/node_modules/request-promise-core/lib/errors.js:14:15)
2020-03-13T06:02:53.784230+00:00 app[web.1]: at Request.plumbing.callback (/app/node_modules/request-promise-core/lib/plumbing.js:87:29)
2020-03-13T06:02:53.784231+00:00 app[web.1]: at Request.RP$callback [as _callback] (/app/node_modules/request-promise-core/lib/plumbing.js:46:31)
2020-03-13T06:02:53.784231+00:00 app[web.1]: at self.callback (/app/node_modules/request/request.js:185:22)
2020-03-13T06:02:53.784234+00:00 app[web.1]: at Request.emit (events.js:311:20)
2020-03-13T06:02:53.784234+00:00 app[web.1]: at ClientRequest.<anonymous> (/app/node_modules/request/request.js:819:16)
2020-03-13T06:02:53.784235+00:00 app[web.1]: at Object.onceWrapper (events.js:417:28)
2020-03-13T06:02:53.784235+00:00 app[web.1]: at ClientRequest.emit (events.js:311:20)
2020-03-13T06:02:53.784236+00:00 app[web.1]: at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at Object.onceWrapper (events.js:417:28)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at TLSSocket.emit (events.js:311:20)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at TLSSocket.Socket._onTimeout (net.js:478:8)
2020-03-13T06:02:53.784238+00:00 app[web.1]: at listOnTimeout (internal/timers.js:549:17)
2020-03-13T06:02:53.784238+00:00 app[web.1]: at processTimers (internal/timers.js:492:7)
2020-03-13T06:02:53.784281+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)`
Here is my app.js file:
require('dotenv').config();
const MyUtil = require("./myutil.js")
const { CommentStream, SubmissionStream, ModMailStream, InboxStream } = require("snoostorm");
const Snoowrap = require('snoowrap');
const Snoostorm = require('snoostorm');
const WatchJS = require("melanke-watchjs")
const r = new Snoowrap({
userAgent: 'abcde',
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
refreshToken: process.env.REFRESH_TOKEN
});
const BOT_START = Date.now() / 1000;
var webController;
function initializeBot(controller){
configReddit();
watchRateLimit();
initCommentStream();
initPostStream();
initInboxStream();
initModMailStream();
webController = controller;
return module.exports
}
function configReddit(){
r.config({continueAfterRatelimitError: true});
console.info("Finished Reddit configuration.")
}
function watchRateLimit(){
//WATCH JS
// var watch = WatchJS.watch;
// var unwatch = WatchJS.unwatch;
// var callWatchers = WatchJS.callWatchers;
WatchJS.watch(r, "ratelimitRemaining",
() => {
if(r.ratelimitRemaining < 50){
console.warn("Rate limit remaining:" +r.ratelimitRemaining);
}
if(webController){
webController.broadcast(r.ratelimitRemaining);
}
});
}
function initCommentStream(){
console.info("Trying to establish comment stream!");
var streamOpts;
try {
streamOpts = JSON.parse(process.env.COMMENT_STREAM_OPTION);
if(!streamOpts || !streamOpts.receiving){
console.info("Comment Stream was disabled, enable through the environment variable.")
return;
}
} catch (error) {
console.log(error);
console.info("COMMENT_STREAM_OPTION unavailable/wrong format.");
return;
}
const comments = new CommentStream(r, streamOpts);
comments.on("item", comment => {
if(comment.created_utc < BOT_START) return;
if(comment.body.toLowerCase().includes("!resolved")){
console.log("New resolved comment!: "+comment.link_id.substring(3))
let flair = {flair_template_id:MyUtil.FLAIR_ID.RESOLVED}
let sub = r.getSubmission(comment.link_id.toString().substring(3));
let reply = ""; //TODO
sub.selectFlair(flair).then(sub.reply())
}
})
console.info("Comment Stream established.");
}
function initPostStream(){
console.info("Trying to establish post stream!");
var streamOpts
try {
streamOpts = JSON.parse(process.env.POST_STREAM_OPTION);
if(!streamOpts || !streamOpts.receiving){
console.info("Post Stream was disabled, enable through the environment variable.")
return;
}
} catch (error) {
console.log(error)
console.info("POST_STREAM_OPTION unavailable/wrong format.");
return;
}
const posts = new Snoostorm.SubmissionStream(r, streamOpts);
//*Listen for items (posts)
posts.on("item", post =>{
if(post.created_utc < BOT_START) return;
console.log("New POST");
console.log(post.body);
notifyNewPost("/u/abcde", post)
//TODO
})
console.info("Post Stream established!");
}
function initInboxStream(){
//TODO
}
function initModMailStream(){
//TODO
}
async function notifyNewPost(peopleList, post){
if(!post._hasFetched){
try {
post = await post.fetch();
} catch (error) {
console.log("Error at notifyNewPost")
console.log(error);
return
}
}
var sendFunction = function(people, post){
r.composeMessage({
to:people,
subject:"New post in r/GoogleAppsScript",
text:`There's a new post in r/GoogleAppsScript:
[${post.title}](${post.url}) posted by ${post.author.name}
`
}).then(()=>{console.log(`New post notification sent to ${people}.`)})
.catch((err)=>{console.log("Error on sending noti to abcde:\n"+err)});
}
if(typeof peopleList == "string"){
sendFunction(peopleList, post);
}else{
for (const people of peopleList) {
sendFunction(people, post);
}
}
}
module.exports={
initializeBot,
r
}
This is web.js:
const controller = {};
var express = require('express');
var app = express();
const wakeDyno = require("woke-dyno");
const bot = require("./app").initializeBot(controller);
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/html/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(port, ()=>{
wakeDyno("https://gas-lighter-bot.herokuapp.com/").start();
console.log('listening on *:'+port);
});
controller.broadcast = (msg) => {
io.emit("ratelimitChanged",msg);
};
The weird thing is the log don't tell me where the error originated in my code, so I am a bit clueless.
I've been running it for a few hours on my machine, but when deployed to Heroku, it throw this error after like 1 minute....
Please help :(
EDIT: This is the error object, it doesn't help me, but maybe it will help you solve this :(
{
name: 'RequestError',
message: 'Error: ESOCKETTIMEDOUT',
cause: Error: ESOCKETTIMEDOUT
at ClientRequest.<anonymous> (/app/node_modules/request/request.js:816:19)
at Object.onceWrapper (events.js:417:28)
at ClientRequest.emit (events.js:311:20)
at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
at Object.onceWrapper (events.js:417:28)
at TLSSocket.emit (events.js:311:20)
at TLSSocket.Socket._onTimeout (net.js:478:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ESOCKETTIMEDOUT',
connect: false
},
error: Error: ESOCKETTIMEDOUT
at ClientRequest.<anonymous> (/app/node_modules/request/request.js:816:19)
at Object.onceWrapper (events.js:417:28)
at ClientRequest.emit (events.js:311:20)
at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
at Object.onceWrapper (events.js:417:28)
at TLSSocket.emit (events.js:311:20)
at TLSSocket.Socket._onTimeout (net.js:478:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ESOCKETTIMEDOUT',
connect: false
},
options: {
gzip: true,
json: true,
headers: { 'user-agent': 'myuseragent' },
baseUrl: 'https://oauth.reddit.com',
qs: { raw_json: 1 },
auth: { bearer: 'myrefreshtoken' },
resolveWithFullResponse: true,
timeout: 5000,
transform: [Function: transform],
uri: 'comments/fhxl4r',
method: 'GET',
callback: [Function: RP$callback],
simple: true,
transform2xxOnly: false
},
response: undefined
}
I get an error when requesting an API and it crashes on any win server. Can anybody help, please?
This is part of my code:
app.get("/js/2806/api/products/getAllDrugs", (req, res) => {
const connection = getDBConnection()
const queryString = "SELECT * FROM tbl_drug";
connection.query(queryString, (err, rows, fields) => {
if (err) {
console.log("Failed to query for drugs: " + err);
// res.sendStatus(500);
res.json({
ErrorDetail: {
code: -1,
msg: err.code
}
});
res.end();
return
}
const drugs = rows.map((row) => {
return {
id: row.id,
storeId: row.drugStoreId,
drugName: row.drugName,
description: row.drugDsc,
drugUsing: row.drugUsing,
drugDoseId: row.drugDoseId,
categoryId: row.categoryId
};
})
res.json({
ErrorDetail: {
code: 0
},
Response: drugs
})
})
});
Error: Connection lost: The server closed the connection. at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:112:13) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:502:10) at Socket.emit (events.js:194:15) at endReadableNT (_stream_readable.js:1125:12) at process._tickCallback (internal/process/next_tick.js:63:19) Emitted 'error' event at: at Connection._handleProtocolError (C:\Users\Administrator\AppData\ ainCure\node_modules\mysql\lib\Connection.js:425:8) at Protocol.emit (events.js:189:13) at Protocol._delegateError (C:\Users\Administrator\AppData\Local\Ca node_modules\mysql\lib\protocol\Protocol.js:390:10) at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:116:8) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) I— lines matching original stack trace ...] at process._tickCallback Cinternal/process/next_tick.js:63:19> [nodemon I - wait in is (nodemon] si ing 'node app.js -erver is running on port: 3000 ode events.js:174 throw er; // Unhandled 'error' event is (nodemon] starting 'node app.js' -erver is running on port: 3000
Because of the server is already running on back so we do have to restart.
and if your using both iterm and the terminal so you need to make sure that the you use only one other one you have to close.
settings.js
exports.dbConfig = {
user: "gpolat",
password: "alphalpha",
server: "DESKTOP-LK9JDJJ",
database: "mydemo",
port: 1433
};
exports.webPort = 9000;
db.js
var sqlDb = require("mssql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new sqlDb.Connection(settings.dbConfig);
conn.connect()
.then(function () {
var req = new sqlDb.Request(conn);
req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
};
Console Error:
Debugger listening on 127.0.0.1:5858
Started Listening at: 9000
{ ConnectionError: Failed to connect to DESKTOP-LK9JDJJ:1433 - connect
ECONNREFUSED 192.168.99.1:1433
at Connection.<anonymous> (C:\Users\Gokhan\documents\visual studio
2015\Projects\SampleREST\SampleREST\node_modules\mssql\lib\tedious.js:378:25)
at Object.onceWrapper (events.js:290:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Connection.socketError (C:\Users\Gokhan\documents\visual studio
Projects\SampleREST\SampleREST\node_modules\tedious\lib\connection.js:531:1
4)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1281:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'ConnectionError',
message: 'Failed to connect to DESKTOP-LK9JDJJ:1433 - connect ECONNREFUSED
192.168.99.1:1433',
code: 'ESOCKET' }
I get this error while creating the rest API via sql server.
"500: Internal Error. Details: ConnectionError: Failed to connect to DESKTOP-LK9JDJJ:1433 - connect ECONNREFUSED 192.168.99.1:1433"