Catch error on IBM Watson IoT NodeJS client - javascript

I'm using the IBM Watson IoT NodeJS client to connect and use IBM Watson IoT.
This works when my object with credentials etc. is correct:
var client = new ibm_watson_iot.IotfGateway(MY-JSON-OBJECT-WITH-CREDENTIALS);
But if credentials is wrong, then I get:
events.js:160
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND 1234xyz.messaging.internetofthings.ibmcloud.com 1234xyz.messaging.internetofthings.ibmcloud.com:8883
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
error: Forever detected script exited with code: 1
How do I correctly catch this error in a nice way?

You can always use try/catch block to handler error like that
try{
var client = new ibm_watson_iot.IotfGateway(MY-JSON-OBJECT-WITH-CREDENTIALS);
}
catch(error) {
console.log("Error in connection.. Probably configuration object")
}

Related

Why nodejs is not allowing me to access other route when I access the root route?

I am using the HTTP module of nodejs to create three routes('/','/about' and the last one treats any other route that is not defined as error route). When I access the root route first and try to access other route nodejs throw an error but when I access the error route or the about the route and try accessing another route it works fine.
Below are the code I wrote and the error nodejs throw
Error
PS C:\Users\Maxwell\Desktop\node> node app.js
node:events:368
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (C:\Users\Maxwell\Desktop\node\app.js:10:9)
at Server.emit (node:events:390:28)
at parserOnIncoming (node:_http_server:951:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
PS C:\Users\Maxwell\Desktop\node> node app.js
node:events:368
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (C:\Users\Maxwell\Desktop\node\app.js:10:9)
at Server.emit (node:events:390:28)
at parserOnIncoming (node:_http_server:951:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
Code
const http = require('http');
const server = http.createServer((req,res)=>{
if(req.url==='/'){
res.end('Welcome Home Dev, You are loved');
}
if(req.url==='/about'){
res.end('This is the about page')
}
res.end(
`<h1>OOOp</h1>
<p>It seen like this page does not exit</p>
<a href='/'>back to homepage</a>
`
);
});
server.listen(5000);
Change to an if/else so you're only processing one branch of the if per request:
const server = http.createServer((req,res)=>{
if(req.url === '/'){
res.end('Welcome Home Dev, You are loved');
} else if (req.url === '/about') {
res.end('This is the about page')
} else {
res.end(
`<h1>OOOp</h1>
<p>It seen like this page does not exit</p>
<a href='/'>back to homepage</a>`);
}
});
Or, alternately, you could add a return after each res.send() to stop further execution in your request handler after you send a response. Remember, that just because you call res.send() your function still continues to execute so you need to manage control flow so the other code that sends a response doesn't execute once you've already sent a response.

Unable to create MongoDB database using Node.js

I am trying to run the below program to create a mongo database using Node.js by running node app.js.
app.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://hostname:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Below is the error I'm getting :-
(node:20815) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [hostname_fqdn:27017] on first connect [Error: connect ECONNREFUSED 10.127.45.59:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
name: 'MongoNetworkError'
}]
at Pool.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:223:5)
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:562:14
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:995:11
at /root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:32:7
at callback (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:280:5)
at Socket.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:310:7)
at Object.onceWrapper (events.js:313:26)
at Socket.emit (events.js:223:5)
at emitErrorNT (internal/streams/destroy.js:92:8) {
name: 'MongoNetworkError'
}
The file/node_modules/package.json all are located in a CentOS Virtual Machine.
You need to start the MongoDB Service after installing.
Edited:
If you have already started service and connecting mongo via terminal, then try to remove mongo lock file (rm /var/lib/mongodb/mongod.lock) and repair mongod (mongod -–repair). Now start mongo service and see if you can connect. I had similar issue with EC2 and Compass and tried above to resolve.

handle request.js error in node application

I am using request to access data from an api. sometimes, when the api Url is down, node throws error and shuts down with the following error
at ClientRequest.emit (events.js:315:20)
at TLSSocket.socketErrorListener (_http_client.js:426:9)
at TLSSocket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: APIURL
is there any way to handle this and prevent node from exiting?
my code is
const JSONdata= ()=>{
request({url:API_URL2,json:true},(error,response,body)=>{
const data=[]
var jsondata=body
data.push(jsondata)
const data2=JSON.stringify(data)
fs.writeFile('sample.txt',data2,(err) => { if(error){console.log(error} })})
You can use try/catch blocks that will keep your program running when certain functions error out. Here's a link describing how they work!
https://www.w3schools.com/js/js_errors.asp
Firstly request module has been deprecated request deprecated hence you can try some other packages like axios. Also while trying out api as well as database request try to have a try and catch block and in case of error try to have an appropriate error message displayed to the user.
try{
//your code
res.json("success")
}
catch(err){
res.json("Looks like something went wrong")
}

How to handle an ETIMEDOUT in node.js using http2?

My knowledge of node.js isn't very good and I might be missing something obvious.
I need to "crawl" a list of urls (combination of http-https, hosts and ports) for an experiment. One of those urls is not responding (it does locally, so I guess one of the middleboxes is blocking) it, which it's fine but I breaks my app as I'm not able to catch the error:
var http2 = require('http2');
var req = http2.raw.get('http://xxx.yyy.zzz.a:23/', function(response) {
var content = '';
response.on('data', function(chunk) {
content += chunk;
})
response.on('end', function() {
console.log(content);
console.log('end');
});
});
req.on('error', function(error) {
console.error(error);
});
It throws the following Error (catched it with process.on('uncaughtException', ...)):
{ [Error: connect ETIMEDOUT xxx.yyy.zzz.a:23]
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: 'xxx.yyy.zzz.a',
port: 23 }
Error: connect ETIMEDOUT xxx.yyy.zzz.a:23
at Object.exports._errnoException (util.js:814:11)
at exports._exceptionWithHostPort (util.js:837:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1044:14)
Try-catch does not work, because the function is async.
request.on('error') does not seem to catch this error. setTimeout is not implemented in this library.
I think I need to add an event into the TCP connection, but I don't know how.
I'm using node.js 0.12.7 and http2 3.2.0
Any ideas? Really appreciated

Node.js - simple example and EPERM error

var server = require('http').createServer(function(req, res){
});
server.listen(8080);
This simple example return error in console:
node node_server.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: listen EPERM
at errnoException (net.js:670:11)
at Array.0 (net.js:756:28)
at EventEmitter._tickCallback (node.js:192:41)
What is going on?
Port was locked. Topic shutdown.

Categories