Handle Exceptions in node/express not working - node.js

I have a node/express application which I'm trying to catch all exceptions so that the application doesn't just freeze. I created an error by calling a mongoose db when it's not running.
await mongoose.connect(dbUrl, mongooseOptions);
Which gives me the following error then the app crashes
MongoNetworkError: failed to connect to server [localhost:27017] on
first connect
Before that is run, I have the following:
process.on('unhandledRejection', (ex) => {
console.log(ex.name, ex.message);
console.log('UNCAUGHT EXCEPTION! 💥 Shutting down...');
process.exit(1);
});
That unhandled Rejection doesn't seem to run. How can I get it to run on exception?

Use uncaughtException instead of unhandledRejection
process.on('uncaughtException', (ex) => {
console.log(ex.name, ex.message);
console.log('UNCAUGHT EXCEPTION! 💥 Shutting down...');
process.exit(1);
});

Related

I would like to launch my function but when the code returns an error 503 responds to the process exit nodejs

I would like to launch my function but when the code returns an error 503 responds to the process exit
however the function does not restart you know why?
process.on ('unhandledRejection', async (reason, p) => {
console.error ('Unhandled Rejection at: Promise', p, 'reason:', reason);
run();
if(nodeStatusCodes[503]){
process.exit();
}
});
``````````````````````````````

Try to cach UnhandledPromiseRejectionWarning discord.js

i'm trying to catch an discord.js error
This error pops up when internet is off, but i want some clean code instead this messy one...
How can i catch this?
I did really try everything..
code:
(node:11052) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11052) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To termin
ate the node process on unhandled promise rejection, use the CLI flag `--unhandl
ed-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejecti
ons_mode). (rejection id: 2)
(node:11052) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr
ecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
i did try this at the very top :
process.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
aswell this one :
client.on('error', error => {
if (error.code === 'ENOTFOUND') {
console.log(no internet!!)
}
});
I also did try this to see where its from, but nothing shows up its still the same
try {
var err = new Error("my error");
Error.stackTraceLimit = infinity;
throw err;
} catch(e) {
console.log("Error stack trace limit: ")
console.log(Error.stackTraceLimit);
}
Error stack trace limit:
10
(node:11008) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
here is the code i use for now what gives the error.
i just want to catch the error in something like this: (No connection)
const Discord = require('discord.js')
const client = new Discord.Client({ autoReconnect: true });
const opn = require('opn')
const getJSON = require('get-json')
const request = require('request');
const config = require("./config/config.json");
const pushbullet = require("./config/pushbullet.json");
const addons = require("./config/addons.json");
const Registration = require("./config/Reg.json");
client.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
client.login(config.Settings[0].bot_secret_token);
I would try to wrap it with try/catch.
And maybe add the following code to understand better what is happening.
Error.stackTraceLimit = Infinity
Reference:
https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Microsoft_Extensions/Error.stackTraceLimit
Remember to remove it after the problem solved, this is not suitable for production use.
Well i solved it!!
I put this on top and its all solved.
process.on('unhandledRejection', error => {
if (error.code === "ENOTFOUND") { console.log ("No internet connection")}
if (error.code === "ECONNREFUSED") { console.log ("Connection refused")}
//console.log('Unhandled promise rejection:', error.code);
});

Catching an error for an async call

And then when adding a stream, I try to catch an occurring error:
try {
logger.addStream(stream); // ERROR HAPPENS AT THIS CALL
console.info(`TRY activated`);
} catch (e) {
console.error(e);
}
I do get the TRY activated message, but the app still crashes. This leads me to the thought that the async model prevents the try-catch to work here.
I added a callback to the addStream() as follows:
logger.addStream(stream, (err, stream) => {
console.log(err);
});
but this doesn't help either.
Also tried with logger.on('error', (err, stream) => { console.log(err) }); but unsuccessful as well.
I'm getting a getaddrinfo ENOTFOUNDerror:
/app/node_modules/gelf/gelf.js:95
throw err;
^
Error: getaddrinfo ENOTFOUND graylog-server
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
Can I catch that locally? F.e. without adding uncaughtException to my process, etc...

Mongoose ValidationError thrown instead of passed to callback,

Mongoose has started throwing errors for me instead of passing them to my callback?
var newsArticle = new NewsArticle(fields);
newsArticle.save(function(err, newsArticle) {
if(err) return next(err);
res.status(201).json(newsArticle);
});
the callback is never called, and the ValidationError is thrown, crashing the app. Why is this?
events.js:85
throw er; // Unhandled 'error' event
^
No listeners detected, throwing. Consider adding an error listener to your connection.
ValidationError: NewsArticle validation failed

Reconnect to TCP/IP socket on NodeJS

I use "net" library to create TCP connection on my nodeJs.
root.socket = net.createConnection(root.config.port, root.config.server);
I'm trying to handle error when remote server is down and reconnect in Cycle.
root.socket.on('error', function(error) {
console.log('socket error ' + error);
root.reconnectId = setInterval(function () {
root.socket.destroy();
try {
console.log('trying to reconnect');
root.socket = net.createConnection(root.config.port, root.config.server);
} catch (err) {
console.log('ERROR trying to reconnect', err);
}
}, 200);
}
The trouble is that in case of remote server shutdown I still get en error and my nodeJS server stops.
events.js:72
throw er; // Unhandled 'error' event
^ Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
You will need something like this:
var net = require('net');
var c = createConnection(/* port, server */);
function createConnection(port, server) {
c = net.createConnection(port, server);
console.log('new connection');
c.on('error', function (error) {
console.log('error, trying again');
c = createConnection(port, server);
});
return c;
}
In your case you are creating a new connection but you don't attach any error listener, the error is raised somewhere else in the execution loop and can not be caught by the "try / catch" statement.
P.S. try to avoid using "try / catch" statement, error handling in Node.JS is made using error listeners and domains, it can be useful only for JSON.parse() or other functions that are executed synchronously.

Resources