RangeError: Invalid status code: 0 error in node, express? - node.js

if i give error message like this it working fine without problem
res.status(401).send('not found, please register');
but when i change to this one i am getting error
return res.status('EXTINF-10202').json({
'message': 'not found, please register'
});
i am getting error like this
F:\test\node_modules\mongoose\node_modules\mongodb\lib\utils.js:97
process.nextTick(function() { throw err; });
^
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse.writeHead (F:\test\node_modules\on-headers\index.js:
55:19)
at ServerResponse.res.writeHead (F:\test\node_modules\express-session\
index.js:169:17)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.res.write (F:\test\node_modules\compression\index.js
:90:14)
at ServerResponse.res.end (F:\test\node_modules\compression\index.js:1
11:14)
at F:\test\node_modules\express-session\index.js:182:13
at F:\test\node_modules\connect-mongo\lib\connect-mongo.js:365:9
at handleCallback (F:\test\node_modules\mongoose\node_modules\mongodb\
lib\utils.js:95:12)
at F:\test\node_modules\mongoose\node_modules\mongodb\lib\collection.j
s:666:5
at F:\test\node_modules\mongoose\node_modules\mongodb-core\lib\topolog
ies\server.js:795:13
at Callbacks.emit (F:\test\node_modules\mongoose\node_modules\mongodb-
core\lib\topologies\server.js:94:3)
at Connection.messageHandler (F:\test\node_modules\mongoose\node_modul
es\mongodb-core\lib\topologies\server.js:235:23)
at Socket.<anonymous> (F:\test\node_modules\mongoose\node_modules\mong
odb-core\lib\connection\connection.js:259:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)

If you take a look at the ExpressJS source for res.status you will see that the function expects a Number, not a String:
/**
* Set status `code`.
*
* #param {Number} code
* #return {ServerResponse}
* #public
*/
res.status = function status(code) {
this.statusCode = code;
return this;
};
https://github.com/expressjs/express/blob/9722202df964bfbfc0f579e4baeb5a4e1b43b344/lib/response.js#L57-L68

Related

How to parse error parameter in request callback?

I'm deliberately triggering an error in a stored procedure under certain conditions which I want to catch in my Node.js API which uses the Tedious package.
Code Snippet from API:
let request = new Request(sql, (err)=>{
if (err) {
sqlerr = err;
console.log(typeof(err));
console.log("**RQ-ERROR**", err);
}
});
In the callback of the "Request" object above there is an "err" parameter. The "typeof()" returns "object"; however, when I dump it to the console it looks like this:
**RQ-ERROR** { RequestError: Duplicate entry for specified period
at RequestError (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\errors.js:32:12)
at Parser.tokenStreamParser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\connection.js:723:34)
at emitOne (events.js:96:13)
at Parser.emit (events.js:188:7)
at Parser.parser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at emitOne (events.js:96:13)
at Parser.emit (events.js:188:7)
at addChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:297:12)
at readableAddChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:279:11)
at Parser.Readable.push (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:240:10)
message: 'Duplicate entry for specified period',
code: 'EREQUEST',
number: 50000,
state: 1,
class: 16,
serverName: 'PERSODG2LNN52\\SQLEXPRESS',
procName: 'CreateStatusReport',
lineNumber: 44 }
This almost looks like a JavaScript object but, as you can see, the "RequestError" data isn't quoted nor is there a comma after the text "240:10)" just before the "message" member. I'm not sure if this is a bug in TDS or if I'm just missing something but I cannot access any of the members as it is. I'd have to convert it to a string and parse it which is fine but isn't very elegant.
Suggestions?
as you can see, the "RequestError" data isn't quoted nor is there a comma after the text "240:10)"
These are artifacts of the console logging out the error message. You can try it out for yourself with something like the following:
$ node
> console.log(new Error('this is an error object!'));
Error: this is an error object!
at repl:1:13
at Script.runInThisContext (vm.js:119:20)
at REPLServer.defaultEval (repl.js:332:29)
at bound (domain.js:395:14)
at REPLServer.runBound [as eval] (domain.js:408:12)
at REPLServer.onLine (repl.js:639:10)
at REPLServer.emit (events.js:194:15)
at REPLServer.EventEmitter.emit (domain.js:441:20)
at REPLServer.Interface._onLine (readline.js:290:10)
at REPLServer.Interface._line (readline.js:638:8)
I'm not exactly sure what the desired outcome of this question is, but try inspecting the err.message property rather than using the typeof operator.

Discord Bot crashed after some time

So I have a discord bot which works perfectly fine, but after some time (about 30 minutes) the bot crashes with this error message:
Error: Unhandled "error" event. ([object Object])
at Client.emit (events.js:186:19)
at WebSocketConnection.onError (C:\Users\Paul\Desktop\Hype-Bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:374:17)
at WebSocket.onError (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\event-target.js:128:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)
at _receiver.cleanup (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\websocket.js:211:14)
at Receiver.cleanup (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\receiver.js:557:13)
at WebSocket.finalize (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\websocket.js:206:20)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
Does someone know how to solve this?
I've been looking for someone who needs some help with this sort of thing, and lo and behold here you are. I too have run into this issue. You have a network error that happens when your bot sends something called a heartbeat to the servers to say to them: i am online. Then the server will send it back. If it is sent and there is not a message returned from the server then it will give you your error. All you have to do is go into the following path in your bot folder /node_modules/discord.js/src/client/websocket/WebSocketConnection.js
Then in that file go to a section that looks like this:
onError(error) {
if (error && error.message === 'uWs client connection error') {
this.reconnect();
return;
}
/**
* Emitted whenever the client's WebSocket encounters a connection error.
* #event Client#error
* #param {Error} error The encountered error
*/
this.client.emit(Constants.Events.ERROR, error);
}
and what I did is change it to this:
onError(error) {
if (error && error.message === 'uWs client connection error') {
this.reconnect();
return;
}
console.log("Attempting to reconnect!")
return this.reconnect()
/**
* Emitted whenever the client's WebSocket encounters a connection error.
* #event Client#error
* #param {Error} error The encountered error
*/
this.client.emit(Constants.Events.ERROR, error);
}
I hope this helps!
Wishing you luck,
Zaedus

Scraping a batch of pages with node horseman: some exceptions aren't catched

I'm using nodejs with horseman to scrape a list of (known to be valid) urls, performing the same scraping operation on all of them in sequence.
I try to catch the errors, but sometimes some exception still slips through and hangs the script. I can run the same urls 'batch' successfully once and get errors another time.
So far I've tried:
- catching errors with catch;
- using the promiseRetry module to retry the promise
- using opening and closing a new horseman instance for every scrape operation
// users: [ { href: '?id=abc123' }, ... ]
// queuePromise: function which returns a chain of promises from an array of functions with callbacks
// promiseRetry: used to retry a promise :3, see promiseRetry documentation
fetch = function(users, options){
var baseUrl = 'https://www.somedomain.com/Users'
var user_queue = []
var items = []
var ci = 0
users.forEach(function (u){
u.url = baseUrl + u.href
user_queue.push(function (next){
promiseRetry(options, function (retry, number) {
var error = true
var horse = new Horseman()
horse
.open(u.url)
.catch(retry)
.evaluate(scrapeitems)
.then(function (_items){
error = false
console.log('Scraped user', ++ci, ':', u.url, ':\n\tfound ' + _items.length + ' items')
if (_items && _items.length) {
items = items.concat(_items)
}
})
.finally(function () {
horse.close()
if (error && number < options.retries) {
retry()
} else {
next()
}
})
})
})
})
return _t.queuePromise(user_queue).then(function (){ return items })
}
here is the uncaught error:
[...]
Scraped user 22: https://www.somedomain.com/Users?id=abc123 :
found 1 items
Unhandled rejection Error: Retrying
at createError (/Users/andrea/src/userscraper/node_modules/err-code/index.js:4:44)
at /Users/andrea/src/userscraper/node_modules/promise-retry/index.js:34:27
at Horseman.<anonymous> (/Users/andrea/src/userscraper/modules/fetcher.js:179:110)
at PassThroughHandlerContext.finallyHandler (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/finally.js:56:23)
at PassThroughHandlerContext.tryCatcher (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/promise.js:689:18)
at Async._drainQueue (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:570:20)
at tryOnImmediate (timers.js:550:5)
at processImmediate [as _immediateCallback] (timers.js:529:5)
Unhandled rejection Error: Failed to load url
at checkStatus (/Users/andrea/src/userscraper/node_modules/node-horseman/lib/index.js:292:16)
at tryCatcher (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/util.js:16:23)
at Function.Promise.attempt.Promise.try (/Users/andrea/src/userscraper/node_modules/node-horseman/node_modules/bluebird/js/release/method.js:39:29)
at Object.loadFinishedSetup [as onLoadFinished] (/Users/andrea/src/userscraper/node_modules/node-horseman/lib/index.js:290:43)
at /Users/andrea/src/userscraper/node_modules/node-phantom-simple/node-phantom-simple.js:636:30
at Array.forEach (native)
at IncomingMessage.<anonymous> (/Users/andrea/src/userscraper/node_modules/node-phantom-simple/node-phantom-simple.js:617:17)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)

Neo4j's NPM component blows up without error

I'm using the thingdom/node-neo4j module like this:
var neo = require('neo4j');
var db = new new.GraphDatabase(...);
but when I call the cypher method with some invalid script, instead of returning an error (allowing me to handle it), it blows up:
db.cypher('// invalid cypher script', (err, res) => {
if (err) console.log('ERROR: ' + err);
console.log(res);
})
what I get is a stack trace that looks like this:
/Users/ekkis/dev/test/inc/node_modules/neo4j/lib-new/errors.js:20
Error.captureStackTrace(this, this.constructor);
^
TypeError: Error.captureStackTrace is not a function
at ClientError.Error [as constructor] (/Users/ekkis/dev/test/inc/node_modules/neo4j/lib-new/errors.js:20:13)
at new ClientError (/Users/ekkis/dev/test/inc/node_modules/neo4j/lib-new/errors.js:81:48)
at Function.__dirname.Error.Error._fromObject (/Users/ekkis/dev/test/inc/node_modules/neo4j/lib-new/errors.js:70:14)
at /Users/ekkis/dev/test/inc/node_modules/neo4j/lib-new/GraphDatabase.js:302:25
at Request._callback (/Users/ekkis/dev/test/inc/node_modules/neo4j/lib-new/GraphDatabase.js:92:20)
at Request.self.callback (/Users/ekkis/dev/test/inc/node_modules/request/request.js:187:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request. (/Users/ekkis/dev/test/inc/node_modules/request/request.js:969:12)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
I'm using node v7.3.0 and posted an issue with the maintainer here: https://github.com/thingdom/node-neo4j/issues/214 but so far no solution. is anyone else running into this? any solutions?

How to not show stack trace in Gulp task error callback?

When I error out in one of my tasks:
gulp.task('foo', function(onDone) {
onDone('It did not work');
});
I get a large irrelevant stack trace:
[13:10:25] 'foo' errored after 4.27 s
[13:10:25] Error: It did not work
at formatError (C:\npm\node_modules\gulp\bin\gulp.js:169:10)
at Gulp.<anonymous> (C:\npm\node_modules\gulp\bin\gulp.js:195:15)
at emitOne (events.js:96:13)
at Gulp.emit (events.js:188:7)
at Gulp.Orchestrator._emitTaskDone (D:\Code\my-project\node_modules\orchestrator\index.js:264:8)
at D:\Code\my-project\node_modules\orchestrator\index.js:275:23
at finish (D:\Code\my-project\node_modules\orchestrator\lib\runTask.js:21:8)
at cb (D:\Code\my-project\node_modules\orchestrator\lib\runTask.js:29:3)
at D:\Code\my-project\gulp-tasks\insert-docs.js:116:25
at Request._callback (D:\Code\my-project\gulpfile.js:112:17)
How do I not show that? I'd prefer to use the in build gulp features rather than a third party module or console.error().
Gulp checks for the presence of a showStack property on Error objects passed to the callback. This was probably introduced to support that option on gutil.PluginError, but can be used with any Error object:
function withError(msg) {
var err = new Error(msg);
err.showStack = false;
return err;
}
gulp.task('foo', function(done) {
done(withError('It did not work'));
});

Resources