Error catching in NodeJs - javascript

I've been working on a project, a socket server, using NodeJS, with some great help from people on this site, my project is nearing completion, but I have an error generated on my code every once in a while, and I can't seem to pin point the error down, since the error log does not give a name of a variable, function or anything related to the problem, it just throws off this message:
Exception: TypeError: Cannot read property '0' of undefined
My problem also arises from the fact that there is nothing much moving in my code unless someone is connected to it, I do have an interval that runs every 4 minutes and send an update query to my DB so the connection to the DB will stay alive (we don't want to change the mySQL server wait_timeout since we use the same DB for other projects and products that needs it that way), and a kind of a global timer also set with setInterval that execute actions being sent to it from dynamicaly created game rooms, but again, the error pops up even if simply restart the service, and leave it untouched, it will come up every 10-20 minutes or so...
So far I've been using this simple code to catch errors:
process.on('uncaughtException', function(err){
_log('Exception: ' + err+"<br>");
});
but this does not give the information I need to know how to debug and find the problem.
My question is is there another way to handle these errors in a way that will return a little more information about the nature of the problem?
Thanks!

The err argument holds more properties like err.message and err.stack.

Related

{node / discord js} Restarting bot's entire script on error

So I'm trying to have my bot restart ENTIRELY on encountering an error. The reason why I don't just let it sift through connection errors is because, whenever I encounter an internet issue, code starts repeating multiple times since the original node process hasn't been terminated, which technically I could fix but other connections to external apis stop working too. So ignoring fixing singular issues, I just want to restart entirely.
What I'm doing currently is using node child_process, with this function:
spawn(process.argv.shift(), process.argv, {
cwd: process.cwd(),
detached : true,
stdio: "inherit"
});
process.exit();
I do know stdio inherit does nothing, since its exiting the parent process, but it doesn't really change anything to put it to ignore so i've just left it. Basically this works in theory, if I use a command to execute this, i can do it over and over and over and it will work fine, singular discord client, no repeats, it's up, i just can't monitor it since my original terminal is disconnected, and I can use a command to exit the current process so it's not stuck since I don't have a terminal to ctrl-c. But once put in practice, executing the function in bot.on("error") by disconnecting my internet seems to work, it ends the first process, but upon regaining internet there is no client connected.
My guess here: bot.on("error") will not be re-executed in the next process due to no discord client being made.
So I don't know if I'm making this too complicated or if I need to add a lot more. If this is the best way to do it then all I would need to solve is to wait until I have internet back and then make a new process or something like that. I'm not educated in fiddling with node so if any answers could be beginner friendly (mainly for node) i'd really appreciate it.
bot.on("error", (err) => {
process.exit(0)
});
Should work, it'll restart the bot when there's an error.
Unsure what you mean by
My guess here: bot.on("error") will not be re-executed in the next process due to no discord client being made.
As long as you bot it in the same code as your startup, it'll restart the bot.
If you use a batch-file to run your bot simply add :a before the node . and goto a at the end.

Is it possible to get request information from a rxjs-timeout-error?

I'm trying to improve our current implementation of error handling and one part of it is the better description of errors in general and also in testing environments. I do this for an Ionic app but since my problem lies within the rxjs timeout-method, I think this is neglectable.
One part im currently stuck on is the correct visualization (error message) of timeout errors since they don't seem to contain anything of value at all. I'd like to show to the user which request was the origin of the timeout error when the error happens and the user sees. In the case of testing environments additional thinks like url, device-version, etc. should be shown as well.
But all the Timeout-Error contains seems to be a stacktrace of the javascript library beneath handling the post request.
So, my question is if there is a way to add or retrieve additional information from an rxjs timeout error?
Below you can see how the TimeoutError from rxjs looks for me.
Thanks!
TimeoutError has nothing to do with values emitted by the source Observable. Still, it's thrown when there are no emissions from the source so what how could it contain any information anyway.
What you can do however is use catchError to get the error that produced, turn it into another error and send it further with throwError:
...
catchError(e => throwError({...e, ...whatever}))
You can for example check whether the error is an instance of TimeoutError and if it is the do something with it.

Non existing property: EventEmitter memory error instead of proper error message

In a NodeJS 6.10.2/SailsJS 0.12.13 based JavaScript application I experience since several months a strange error behavior.
In a Sails controller, I try to retrieve a property of a literal object:
console.log(someObject.someProperty);
console.log("I am still here!");
However, in my case someObject is undefined. So, I'd expect to get an error like 'Cannot read property someProperty of undefined.' - and then either Node.js to stop completely or the code to go on (with the next console.log).
Instead, the code simply stops executing at that point and I get a strange warning: "(node:4822) Warning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit." It is however, unpredictable how often this error occurs. Somethings only once, somethings about 20 times right after each other.
What I found out so for is that it is somehow connected to the question whether there was already a response or not. Consider the following:
mySailsControllerFunction: function(req, res) {
console.log(someObject.someProperty);
console.log("I am still here!");
res.json({"foo":"dahoo"});
}
This will result in Sending 500 ("Server Error") response: ReferenceError: someObject is not defined - exactly what I expect.
However, now I first send some response and then trying to access my non existing property, turning the code into:
mySailsControllerFunction: function(req, res) {
res.json({"foo":"dahoo"});
setTimeout(function () {
console.log("Yeah!");
console.log(someObject.someProperty);
console.log("I am still here!");
},1000);
}
then I often get simply nothing: 'Yeah!' displayed, but nothing comes afterwards. The event listener error is sometimes there, sometimes not. Very strange.
Additionally, and strange enough, the problem seems to be somehow connected to the time passed since the start of Sails. I put the code you see above inside a Sails controller function which is called immediately after the clients re-connect. I then played around with the timeout values, restarting the Sails server several times. Outcome: If I set the timeout to 1s, in 4 of 5 tests, I will get the correct error behavior. For 10 seconds it is about 50%, for 30s the error will always be ignored without any console output.
However, if I put my test code outside of the Sails controller, I always get the correct error behavior by Node. So, I'm quite sure this is a wrong behavior of Sails, not Node.
Disclaimer: I don't know Sails. So it may or may not be related, but my answer may offer a clue.
From the Sails documentation:
http://sailsjs.com/documentation/reference/response-res/res-json
This method is terminal, meaning it is generally the last line of code
your app should run for a given request (hence the advisory usage of
return throughout these docs).
Thus, when you use res.json({"foo":"dahoo"});, Sails probably sends the response back to the client, closing the call sequence, which, if it uses Promises or some other async mechanism, may kind of "swallow" further code, as also suggested in an above comment. This is probably internal coding in Sails, so it's not immediately obvious from the outside WHY your second code block specifically doesn't work.
So you should stick to the first pattern: access your property first, and put res.json() at the end of the controller function.
For reference: I finally solved that issue.
There were, somehow hidden in the code, process exit handlers defined:
process.on('exit', myErrorFunction.bind());
process.on('SIGINT', myErrorFunction.bind());
process.on('uncaughtException', myErrorFunction.bind());
The problem was: The function in which these lines were in was bound to a cronjob. So, each time the cronjob executed, new handlers were registered. So, my assumption above (before vs. after response) was wrong: In fact everything worked till the cronjob was executed for the first time. From then on, it didn't. And eventually, the warning was fired (correctly!).
I would have never found out without this answer: Make node show stack trace after EventEmitter warning
You have to add one line of code to get the stack trace:
process.on('warning', e => console.warn(e.stack));
Additionally, speaking of stack traces: In the Sails serverError response (api/api/responses/serverError.js), it is convenient to access it like this:
module.exports = function serverError (data, options) {
console.log(data.stack);
/* ... */
};

Node.js error handling with socket.emit

I have some node.js client side code like this:
socket.emit('clickAccept', { myrecid: recid });
Server side node.js code gets it fine and all is well.
If I take the server down to simulate a server side outage, then click the button that fires this socket.emit on the client side, this happens:
Nothing really, I guess it might eventually time out
When I bring the server back up, the clicks end up being sent to the server and the server acts on them (TCP-like I Guess).
What I want to happen is for those socket.emit calls to die after a short timeout and not send when the server comes back up, it causes all sorts of confusion because if they click 3 times, nothing happens, then when/if the connection or server comes back up they get 3 reactions all at once.
Also, if they click and it times out because the server is down, I would like to show an error to the client user to let them know that basically the click didn't work and to try again.
I know how to act on and show an error if the socket goes down but I don't want to do this if they aren't trying to click something at that time. No sense is firing errors at the user because the socket went down briefly if they have no need to do anything at that moment.
So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.
Thanks in advance and I hope that was at least reasonably clear.
The root of your issue is that socket.io attempts to buffer any data that it can't currently send to the server (because the connection to the server is disconnected) and when the server comes back up and the connection is restored, it then sends that data.
You can see the technical details for how this works here: socket.io stop re-emitting event after x seconds/first failed attempt to get a response
You have several implementation options:
If socket.io already knows the client is not connected to the server, then don't buffer the data (perhaps even give you back an error to show to your user).
When socket.io reconnects and there was data buffered while the connection was down, clear that data and throw it away so old data isn't sent on a reconnect.
Implement a timeout to do one of the above after some sort of timeout.
So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.
Probably, the simplest way to do that is to implement a version of what is shown in the above referenced answer:
Socket.prototype.emitWhenConnected = function(msg, data) {
if (this.connected) {
this.emit(msg, data);
return null;
} else {
return new Error("not connected");
}
}
Then, switch your code from using .emit() to use .emitWhenConnected() and check the return value when using it. If the return value is null, then no error was detected. If the return value is not null, then there was an error.
Thanks for the other answers and help. I ended up solving this in a super simple way. See below:
if (socket.connected){
// Do your thing here
} else {
// Throw error here that tells the user they're internet is likely down
}
Hope this helps someone out there, it was a huge improvement in our code to make sure that user's are getting proper feedback when if they have brief network/internet outages.

Firebase error after logout

I'm currently developing a little Website with Firebase. I got a couple of HTML files and each file contains a logout button which calls the function
function logout(){
auth.logout();
console.log("logout successfull");
location.href="index.html";
}
After getting redirected I tried to login again but it always failed with the following error message:
Error: FirebaseSimpleLogin: An unknown server error occurred.
It took me some time to realise that the redirection to the index page caused the problem. When I delte the location.href="index.html"; line, everything works fine.
Problem is, I really need something that redirects me to the front page, when the user isn´t loged in. Is this a known problem and/or can someone come up with a solution to this problem?
Thanks in advance :)
PS.: I realised that I could "fix" the problem (after getting redirected to the index page) when I cause an error (f.e. calling a undefined function). Idk if this information helps...
Ok, thanks for your reply Kato!
I changed quite a lot, since I started the "project". Instead of using mutliple HTML files I copied everything into the index.html and work now with mutliple (hidden) DIVs.
But unfortunatly, the problem still exists.
I offer two different Login possibilites. One with Facebook (works 100% of the time for me) and one with the SimpleLogin (works barely).
I´m pretty sure I did the initialization the same way like it´s done in the tutorials on firebase.com.
This is how I connect to the Firebase DB
var ref = new Firebase('https://partyfinder-db.firebaseio.com/');
var auth = new FirebaseSimpleLogin(ref, function(error, user) {
if (error) {
// an error occurred while attempting login
alert(error);
} else if (user) {
// Here I work with user.id etc.
} else {
// user is logged out
}
});
And that is how I try to login the user...
function login() {
//I probably should use jQuery here...
var _email = document.getElementById("emailLogin").value;
var _pw1 = document.getElementById("passwordLogin").value;
var _rememberMe = document.getElementById("rememberMe").checked;
auth.login('password', {
email: _email,
password: _pw1,
rememberMe: _rememberMe
});
showMain(); //Hide and show DIVs and stuff...
}
I call this function on the SignIn Button. The whole Javascript file is linked in the head part of the HTML file.
So, calling this function is normally causing the following error
Error: FirebaseSimpleLogin: An unknown server error occurred.
I already figured out that this message only shows up when the connection to the DB already was successful. For example, when I type in an invalide email adress, the following message appears:
Error: FirebaseSimpleLogin: The specified user does not exist.
There are a few things that can "fix" the problem. For example, when I use the Facebook Login and logout after this was successful, I can sign in using firebase simpleLogin. Sometimes (unfortunatly not always) it helps when I`m causing an error, f.e. calling a non existing function. After the error message is displayed in the console, I can continue logging in (successfully).
But to be honest I`ve absolutly no idea what this tells me about the error and if this is somehow a hint to the solution. I also tried to set some breaking points and debug through the relevant code (using google chrome) but didn´t find anything.
I uploaded the page to a free webspace, where you can test this whole thing by yourself.
But please note, this project is just for testing purpos. I´m not planning to release it somehow, it´s just for me to figure out multiple things and I find it easier to learn something when I can set it in a context. I´m pretty sure it´s quite bad coded and contains many mistakes, etc. But I´m always grateful for feedback beside the actual problem :)
For the login you can use
email: user#email.com
password: user
If you use the FB-Login, your Name and your email adress will be saved to the Database (but I can delete this section of the code if you want/need to use it and feel uncomfortable about it).
http://partyfinder.lima-city.de/
Most of the comments are in german, sorry for that...

Categories

Resources