Catch exception in node.js - javascript

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.

Related

Why doesn't Node.js throw an error when it can't connect to socket?

When i call both of these functions only the upper one fails and returns an error
const { Socket } = require("net")
class Client {
connect () {
this.a = new Socket()
this.a.connect(this.port, this.host)
this.socket = new Socket()
this.socket.connect(this.port, this.host)
}
}
The problem is, that i know that the port this should connect to, is not used. Both functions should throw an error.
If i call the lower one first, still the one with this.a fails.
If i use this.socket for both, the first one always fails even if i change the order of them.
To differentiate between them i used a different port to connect to but also unused.
this.socket = new Socket()
this.socket.connect(6743, this.host)
this.a = new Socket()
this.a.connect(6744, this.host)
The this.port and this.host variables are not the problem, because if run the script while the server on the port is online it works.
Error Message that should be thrown:
events.js:291
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:6744
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)
Emitted 'error' event on Socket instance at:
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: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 6744
}```
Like other users have mentioned, the second error is not being triggered because the application effectively stops running after the first error. To prove this, you could try putting a console.log between your two attempts to connect to a socket and see that won't run as expected either.
In nodeJs some module throw error in event
Socket throw error in event.on('error') and you should checked event
I hope below link help you:
https://stackoverflow.com/a/25847067/6759368

Handling an error on a tcp connection using the "net" module of NodeJS

Im trying to learn the "net" module of NodeJS, but i have run into an annoying problem. My code is in 2 scripts.
//index.js
var net = require("net")
var server = net.createServer(socket=>{
socket.write("Hello!")
})
server.on("error", err=>{
console.error(err)
})
server.listen(50001)
and
//client
var net = require("net")
net.createConnection({
host:"localhost",
port: 50001
})
.on("data", data=>{
console.log(data.toString())
})
when i run the 2 scripts...
node index.js
node client.js
...the message "Hello!" is sent to the client with no problems. If i CTRL+C out of the client (to simulate an unexpected closure), i get the following error
events.js:174
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
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)
which i find strange, as I have registered an "error" event on the server. What am i doing wrong?
The program registers a handler for an 'error' event on the server's listening socket, but it does not register an 'error' handler on the separate new socket that is created to carry the connection that is made by the client. (Every connection to the server gets a separate new socket, distinct from the listening socket and from any other connections that have been made earlier.)
That new connection socket is the one that is passed as the argument to the server's connect handler. It's the socket that you write 'Hello!' into.
If you want the program to be notified of an error on that new socket then you must register an 'error' handler on the new socket. Something like this:
var net = require("net")
var server = net.createServer(socket=>{
socket.on('error', err=>{
console.error('connected socket: ' + err);
});
socket.write("Hello!")
})
server.on("error", err=>{
console.error(err)
})
server.listen(50001)
Similarly, if you wanted the server to read data from the connection then you would register a handler for the 'data' event on the new connection socket, in the same way as you already did on the client's socket.

Node.js and Zaproxy UnhandledPromiseRejectionWarning: RequestError: Error: socket hang up

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)

How to prevent "Error: connect ECONNREFUSED"

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

Why am i getting this error running 'net' module node.js

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.

Categories

Resources