I am new to node.js and am trying to experiment with basic stuff.
My code is this
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
Here's the question - how can I see the exceptions thrown (or events thrown) when calling createServer ? I tried try/catch but it doesn't seem to work . In module's API I couldn't find any reference to it . I am asking because I accidentally started a server on a taken port(8888) and the error I got (in command-line) was Error : EDDRINUSE , this is useful enough but it would be nice to be able to understand how errors are caught in node .
You can do this by handling the error event on the server you are creating. First, get the result of .createServer().
var server = http.createServer(function(request, response) {
Then, you can easily handle errors:
server.on('error', function (e) {
// Handle your error here
console.log(e);
});
Print stacktrace of uncaught exceptions using following code.
process.on('uncaughtException', function( err ) {
console.error(err.stack);
});
The error is emitted in the listen() method. The API documentation includes an example just for your situtation.
You can use
process.on('uncaughtException', function(e){
console.log(e);
});
To handle uncaught exceptions. Any unhandled exception from the web server could be caught like this.
Related
var zapClient = require('zaproxy');
const zapOptions = {
key : 'abcdefghijklmn',
proxy : 'http://localhost:8090/'
};
const zaproxy = new zapClient(zapOptions);
zaproxy.spider.scan("https://www.google.co.in");
i am trying to run above code i am getting :
(node:8380) UnhandledPromiseRejectionWarning: RequestError: Error: socket hang up error.
i have tried socket hang up error with nodejs and "Request error: Socket hang up" with nodeJS on Amazon EC2 didn't help.
I believe changing the last line of your code to this should fix the problem:
zaproxy.spider.scan("https://www.google.co.in", (err, res) => {
if (err) throw err;
//do something with res here
});
//can't do anything with res here
Also check the zap.log file - that might be logging errors which by default are not reported to the client (for security reasons - this can be disabled for testing)
I'm currenlty working on a TS3 query bot written in node.js.
I added an auto reconnect to it but I have the issue now that the bot crashes if the server is offline with the following error:
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
The line which starts the connection is the following:
var cl = new ts3.TeamSpeakClient(config.serverIP);
used with the node-ts api -> https://github.com/nikeee/node-ts
I already added the following events:
cl.on('error', function(err){
console.log("bla: " + err)
});
cl.on('uncaughtException', function (err) {
console.log(err);
});
uncaughtException doesn't get triggered and error doesn't prevent the crash.
How can I prevent it from crashing?
Edit: It's async btw.
You need to catch the UncaughtException on the process rather than in ts3 object.
process.on('uncaughtException', function (err) {
console.log(err);
})
More on handling exceptions can be found over here.
UPDATE:
cl has its own fail promise as well. To be implemented like this:
cl.fail(function(err) {
console.log("An error occurred." + util.inspect(err))
});
For some reason this request GET never returns, but only in Node.js. I've tried in browser, curl, httparty, ruby's Net::Http, postman, clojure and they all work fine. Node.js will not.
This will return as you'd expect
echo "require('https').get('https://github.com/jakecraige.json', function(res) { console.log(res); });" | node
This never will return, it eventually throws an ECONNRESET
echo "require('https').get('https://gateway.rpx.realpage.com/rpxgateway/PricingAndAvailability.svc?wsdl', function(res) { console.log(res); });" | node
If anyone could provide some insight into this that would be extremely helpful.
Thanks!
Zyrri in IRC directed me to here which solved the problem.
SSL Error in nodejs
Looks like it wants SSLv3_method from node.js
$ curl 'https://gateway.rpx.realpage.com/rpxgateway/PricingAndAvailability.svc' -I
HTTP/1.1 400 Bad Request
Try providing an error handler and see what you get.
Your code hangs for me whichever URL I pick. I believe that's node trying to make sure we don't exit prematurely, running its event loop just in case. All other techniques you listed are synchronous, not event-driven. Also, res is probably not what you want to print, since it's the node's internal response object. Try this:
cat <<EOF | node
require("https").get("https://github.com/jakecraige.json",
function(res) {
var body = ''
res.
on('data', function(data) { body += data}).
on('end', function() { console.log(body); process.exit(0); });
}
);
EOF
Combining #Constarr links with this original post I have this constructed request getting a valid response.
var https = require('https');
https.globalAgent.options.secureProtocol = 'SSLv3_method';
https.get("https://gateway.rpx.realpage.com/rpxgateway/PricingAndAvailability.svc?wsdl", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Docs here
I am using .net modular and opening tcp port on 6112.
var net = require('net');
var server = net.createServer(function (socket) { //'connection' listener
});
server.listen(6112, function () { //'listening' listener
console.log('server started');
});
On the same machine i start a java socket in main.
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("Connecting...");
Socket socket = new Socket("localhost", 6112);
System.out.println("Connected");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get this exception,
C:\Users\Mustafa\WebstormProjects\Node.Js>node hello.js
server started
events.js:72
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:884:11)
at TCP.onread (net.js:539:19)
Is this like a bug or something, cause if once i get through this bug, I will be good thanks.
I haven't used the debugger cause as Ryan said it him self a year ago that it is still shitt.
You need to listen for errors on the socket. Node has the default behavior that when something does .emit('error'), if there are no error handlers attached, it will throw the error instead, thus crashing the application.
var server = net.createServer(function (socket) {
socket.on('error', function(err){
// Handle the connection error.
});
});
You are creating a socket and connecting from it, but not closing it. So when the program finishes, to node.js it looks like connection is reset (closed abruptly). Call socket.close(); before program finishes.
You can structure your code in this way :
try {
tryStatements //your code that is causing exceptions
}
catch(exception){
catchStatements //handle caught exceptions
}
finally {
finallyStatements //execute it anyways
}
Or if you like to catch uncaught exceptions from runtime, use this (main process won't exit on exceptions)
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
console.log(err.stack);
});
The problem is in java code which is causing node.js to exit on exception. So be sure to add socket.close();. Above is just error handling on node.js part.
I have a simple program, which needs to make sure I can connect to a Redis server. I use node-redis to connect and need to wait until Redis is started. I use this piece of code:
function initializeRedis(callback) {
(function createClient(){
var runner;
try {
client = redis.createClient();
} catch (e) {
setTimeout(createClient, 1000);
}
callback();
})();
};
initializeRedis(function() {
// Work here
});
This is because without the try/catch, I got an exception from node.js:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused
at Socket.<anonymous> (/var/www/php-jobs/node_modules/redis/index.js:88:28)
at Socket.emit (events.js:64:17)
at Array.<anonymous> (net.js:830:27)
at EventEmitter._tickCallback (node.js:126:26)
When I start redis-server (Ubuntu machine) and start this script, everything works fine. If I stop redis-server and start the script, it doesn't catch the exception and still throws this same exception. How is that possible? I have a try/catch statement!
After client = redis.createClient();, set a handler for the error event:
client.on('error', function(err) {
// handle async errors here
});
Have a look at the stack trace - your code isn't in it, so there's no place where a try/catch could catch the error.