Line number error does not show up when using MSSQL Node? - node.js

I have been using MySQL database with Nodejs for a while. I recently switched to MSSQL with Nodejs
When using a try catch block with Nodejs and Mysql any error with the query execution would give me the line at which the error occured
So while using MySQL I did:
try{
await pool.quer(`sql statement`)
}
catch(err){
console.log(err)
}
This would give me an error and the line number of error. But with node-mssql, I get:
{ RequestError: Incorrect syntax near 'Invalid'.
at StreamEvents.req.once.err (C:\Users\David\Main Web\node_modules\mssql\lib\msnodesqlv8\request.js:463:17)
at Object.onceWrapper (events.js:277:13)
at StreamEvents.emit (events.js:189:13)
at errors.forEach.err (C:\Users\David\Main Web\node_modules\msnodesqlv8\lib\reader.js:33:20)
at Array.forEach (<anonymous>)
at routeStatementError (C:\Users\David\Main Web\node_modules\msnodesqlv8\lib\reader.js:26:14)
at invokeObject.end (C:\Users\David\Main Web\node_modules\msnodesqlv8\lib\reader.js:258:13)
at freeStatement (C:\Users\David\Main Web\node_modules\msnodesqlv8\lib\driver.js:160:13)
at cppDriver.freeStatement (C:\Users\David\Main Web\node_modules\msnodesqlv8\lib\driver.js:150:11)
code: 'EREQUEST',
originalError:
{ Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near 'Invalid'. sqlstate: '42000', code: 102 },
name: 'RequestError',
number: 102,
state: undefined }
This is such an unhelpful error. I know where the error is coming from for this error because there is only one sql statement getting executed right now but as my program grows without knowing where the error is coming from it will be hard to debug. Is this an expected behavior of node-mssql?

If you see the documentation here, it clearly mentions what it return in error and what not.
It clearly mentions that "Those errors are initialized in node-mssql module and its original stack may be cropped. You can always access original error with err.originalError"

In your catch block you can try printing the stack trace. That should give you the line number where the error occurred. You can use one of the following statements:
console.stack("---TRACE---")
OR
var stackTrace = new Error().stack
console.log(stackTrace)

Related

How to fix 'events.js :167 error Error: connect ECONNREFUSED 127.0.0.1:443' in Node.js when no other apps seems to be attempting to use the port?

I'm getting the error described below when running my node.js app after perfoming a few api calls.
The error does not always show in the exactly same place/line of code. But most of the times it is at the end of the api call.
events.js:167
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)
Emitted 'error' event at:
at TLSSocket.socketErrorListener (_http_client.js:391:9)
at TLSSocket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
Based on similar questions here at SO my hypothesis is that a) there is something using 127.0.0.1:443 and therefore conflicting with my app or b) node is trying to use 127.0.0.1:443 but there is nothing there for it to use (my app is listening to localhost :3000).
Hyphothesis a) doesn't seem likely since after running netstat -ano | findstr 127.0.0.1:443 nothing shows up (when app is running and right after it terminates).
Also killed every node.exe and mongod.exeb using any port in my computer, closed the terminal and restarted the node app without success.
In case error is related with hypothesis b) I'm not sure how to address it.
api.post('/parsePOpdf', wagner.invoke(function(Pdfeq, Pdfdocspec, Product, User, Order){
return async function(req,res){
//... some code
pdfParser.on("pdfParser_dataError", errData => console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", async function(pdfData) {
fs.writeFile("./test.json", JSON.stringify(pdfData), function(err){
console.log(err);
});
let pages = pdfData.formImage.Pages;
//console.log('pages 557', pages);
let order = {
orderDetails : {
supplier : [{
item : []
}]
}
};
for (const page of pages){
let value = await getItemsInPDF(page, productKeys, pdfParsingDetails, order, Product, customer, supplierLink, User);
//... more code
order = value;
}
return res.json(order);
});
pdfParser.loadPDF(pdfFile);
}
}));
I would expect the code to finish without throwing this error.
It turns out that the problem was in the api code: an http.get line to fetch a remote file was generating the conflict. This makes sense since the error was not present for other endpoints of the api.
So learning is that if the terminal reports no app using the suspected conflicting port (see question) answser should be within the same code and you need to go line by line to identify which one is causing the problem (instead of focusing on other apps trying to use the same port, like I was focusing on).

MongoError: write EPIPE

I'm using Node.JS + Mongoose + MongoDB. Had my app working ok until now, now when trying to save a document:
Saving operation:
doc.save(function(err, d){
console.log(err,d);
{"name":"MongoError","message":"write EPIPE"}
Error stack:
{ [MongoError: server localhost:27017 received an error {"name":"MongoError","message":"write EPIPE"}]
name: 'MongoError',
message: 'server localhost:27017 received an error {"name":"MongoError","message":"write EPIPE"}' } undefined
error: TypeError: Cannot read property 'url' of undefined
at EventEmitter.<anonymous> (/home/ec2-user/c/index.js:160:61)
at EventEmitter.<anonymous> (/home/ec2-user/c/node_modules/mongoose/node_modules/mpromise/lib/promise.js:174:48)
at EventEmitter.emit (events.js:95:17)
at Promise.safeEmit (/home/ec2-user/c/node_modules/mongoose/node_modules/mpromise/lib/promise.js:81:21)
at Promise.reject (/home/ec2-user/c/node_modules/mongoose/node_modules/mpromise/lib/promise.js:109:15)
at Promise.error (/home/ec2-user/c/node_modules/mongoose/lib/promise.js:94:15)
at Promise.resolve (/home/ec2-user/c/node_modules/mongoose/lib/promise.js:112:24)
at /home/ec2-user/c/node_modules/mongoose/lib/document.js:1555:39
at handleError (/home/ec2-user/c/node_modules/mongoose/node_modules/hooks-fixed/hooks.js:40:22)
at next_ (/home/ec2-user/c/node_modules/mongoose/node_modules/hooks-fixed/hooks.js:75:26)
Looks like I'm able to read data, but not to write new documents. Mongo is app and running. I've tried so far, restarting the DB, with no good results.
Just tried to insert from mongo client and worked
> db.mysecretcollection.insert({url:"sampletestremoveme"});
WriteResult({ "nInserted" : 1 })
So it seems to be a Node.js / Mongoose issue.
It seems to me that the document was too big, actually I was able to save it after removing one of its fields. The weird thing is that mongoose should catch that with "Error: Document exceeds maximum allowed bson size of XXX bytes" exception, but that was never thrown.

Node.js buffer + lz4 issues - buffer.js:705 throw TypeError('value is out of bounds')

I have the following line in my node.js script that is generating a fatal error:
var compressedOutput = lz4.encode(new Buffer(logdata,"utf8"));
The variable 'logdata' contains a string I create with http request parameters. Is this an issue with lz4 or the way I'm creating my buffer? How can I resolve? Error message is below:
buffer.js:705
throw TypeError('value is out of bounds');
^
TypeError: value is out of bounds
at TypeError (<anonymous>)
at checkInt (buffer.js:705:11)
at Buffer.writeInt32LE (buffer.js:782:5)
at Encoder._flush (/var/www/node_modules/lz4/lib/encoder_stream.js:210:7)
at Encoder.<anonymous> (_stream_transform.js:130:12)
at Encoder.g (events.js:180:16)
at Encoder.emit (events.js:92:17)
at finishMaybe (_stream_writable.js:359:12)
at endWritable (_stream_writable.js:366:3)
at Encoder.Writable.end (_stream_writable.js:344:5)
worker 3884 died
Thanks and much appreciated!

ForEachLine() in node.js

Referring to slide no 35 in ppt on slideshare
When I run this code
var server = my_http.createServer();
server.on("request", function(request,response){
var chunks = [];
output = fs.createWriteStream("./output");
request.on("data",function(chunk){
chunks = forEachLine(chunks.concat(chunk),function(line){
output.write(parseInt(line,10)*2);
output.write("\n");
})
});
request.on("end",function(){
response.writeHeader(200,{"Content-Type":"plain/text"})
response.end("OK\n");
output.end()
server.close()
})
});
server.listen("8080");
I get error as
chunks = forEachLine(chunks.concat(chunk),function(line){
^
ReferenceError: forEachLine is not defined
Of course I unserstand that I need to include some library but when I googled this I found nothing . Since I am complete newbie to this I have absolutely no idea how to resolve it.
Any suggestions will be appreciable.
EDIT
Using the suggested answer I am getting error as
events.js:72
throw er; // Unhandled 'error' event
^
TypeError: Invalid non-string/buffer chunk
at validChunk (_stream_writable.js:150:14)
at WriteStream.Writable.write (_stream_writable.js:179:12)
at /var/www/html/experimentation/nodejs/first.js:18:20
at Array.forEach (native)
at forEachLine (/var/www/html/experimentation/nodejs/first.js:8:60)
at IncomingMessage.<anonymous> (/var/www/html/experimentation/nodejs/first.js:17:18)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:736:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
Thanks
See proxy_stream.js
function forEachLine(chunks, callback) {
var buffer = chunks.join("")
buffer.substr(0, buffer.lastIndexOf("\n")).split("\n").forEach(callback)
return buffer.substr(buffer.lastIndexOf("\n") + 1).split("\n")
}
The link to the repo was on the first slide.
EDIT BY LET's CODE FOR ERROR MESSAGE
Came to know the actual issue now .
I was using nod v0.10 and it is buggy in getting the streams so I was getting the error. Downgraded to v0.8 and same code is working perfect .

Node Redis Client Not Working With Method "HMSET"

I have the following code block that fails:
this.redisClient.hmset('user:' + userObj.getUserId(), {
'userId' : userObj.getUserId(),
'salutation' : userObj.getSalutation(),
'fn' : userObj.getFn(),
'mi' : userObj.getMi(),
'ln' : userObj.getLn(),
'suffix' : userObj.getSuffix(),
'userType' : userObj.getUserType(),
'created' : userObj.getCreated()
});
The error stack is as follows:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot call method 'hmset' of undefined
at /node_apps/oc/api/v1/routes/user/db.user.js:70:34
at try_callback (/node_apps/oc/api/v1/node_modules/redis/index.js:484:9)
at RedisClient.return_reply (/node_apps/oc/api/v1/node_modules/redis/index.js:555:13)
at HiredisReplyParser.<anonymous> (/node_apps/oc/api/v1/node_modules/redis/index.js:256:14)
at HiredisReplyParser.emit (events.js:67:17)
at HiredisReplyParser.execute (/node_apps/oc/api/v1/node_modules/redis/lib/parser/hiredis.js:43:18)
at RedisClient.on_data (/node_apps/oc/api/v1/node_modules/redis/index.js:440:27)
at Socket.<anonymous> (/node_apps/oc/api/v1/node_modules/redis/index.js:70:14)
at Socket.emit (events.js:67:17)
at TCP.onread (net.js:329:14)
I am running Node 0.6.17 with Node Redis client. Any insight? Thanks!
If Node thinks you're calling hmset on undefined, that means it thinks that this.redisClient is undefined; quite often, this is because the value of this is not what you think it is (although it could be that redisClient wasn't initialized, etc). While it's impossible to say without seeing the surrounding code and how it's called, check to make sure the value of this is bound, if necessary.

Resources