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))
});
Related
I have a file system function which deletes a file then creates a new one with all new data, I am looking for a possible fix for an error that occurs randomly, and not every time, but around every other time. Here is my current code:
try {
if(fs.existsSync(file)) {
fs.unlink(file, function (err) {});
}
} catch (error){
console.log('There was no file to be deleted');
}
fs.open(file, 'w', function (err, file) {
if (err) throw err;
});
var logger = fs.createWriteStream(file, {
flags: 'a' // 'a' means appending (old data will be preserved)
});
which throws the error occasionally:
C:\Users\codel\OneDrive\Documents\BattlEye\index.js:265
if (err) throw err;
^
Error: EPERM: operation not permitted, open 'C:\Users\codel\OneDrive\Documents\BattlEye\files\610636905440215071.txt'
Emitted 'error' event on WriteStream instance at:
at internal/fs/streams.js:375:14
at FSReqCallback.oncomplete (fs.js:171:23) {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\OneDrive\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
First thing that is noticeable is that this is a cloud drive(OneDrive). With my lack of knowledge about permissions, I decided to test out if the problem was in the OneDrive by transferrring the file to my harddrive. The results were not surprising. It didn't change a thing.
C:\Users\codel\Documents\BattlEye\index.js:265
if (err) throw err;
^
[Error: EPERM: operation not permitted, open 'C:\Users\codel\Documents\BattlEye\files\610636905440215071.txt'] {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
But the Emmitted 'error' event on WriteStream disappeared from the error log.
Any ideas on why this error is happening and how to fix it?
It looks like you're using asychronous fs calls. Async calls do not work like that.
You can do a search for NodeJS asynchronous programming.
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.
I have a basic web server with node.js and a root-directory where several .html files are stored. So what I'am doing is
var path = request.url;
getHtmlFile = function(req,res){
fs.readFile('html'+path,funtion(err,data){
if(err){
console.log("no file");
}
else {
res.write(data);
res.end();
console.log("file found");
}
});
}
This code gives me following error :
events.js:141
throw er; // Unhandled 'error' event
^
Error: write after end
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:428:15)
at mypath\server.js:43:18
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)
I'am not very familiar with node.js, so it would be nice, if someone can explain me, what I am missing.
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.