i have implemented a very minimalistic backend service using expressjs and socket.io to transfer serial data readings from an arduino to a react front end. i use SerialPort package to achieve this. my problem is when i try to connect to serial port that is not available or not connected the SerialPort library throws out following error.
(node:940) UnhandledPromiseRejectionWarning: Error: Opening COM6: File not found
(Use `node --trace-warnings ...` to show where the warning was created)
(node:940) 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 terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
this error is completely acceptable and expected because i'm trying to connect to a device that is not exists. but i want to handle this error nicely and notify the fronted that the serial port connection is failed. to achieve this i used a try catch block like following.
io.on("connection", function (socket) {
socket.on("start", function () {
console.log("Device connection starting...");
try {
port = new SerialPort("COM6", { baudRate: 9600 });
parser = port.pipe(new Readline({ delimiter: "\n" }));
} catch (error) {
console.log(error);
io.emit("error", "Can't Connect!");
console.log("error msg sent");
}
});
});
but when the error is thrown this catch block will not run. what can i do to fix this issue ? how can i handle this error ?
Instead of a try-catch-block, use the error event:
port = new SerialPort("COM6", { baudRate: 9600 })
.on("error", function(error) {
console.log(error);
io.emit("error", "Can't Connect!");
console.log("error msg sent");
});
parser = port.pipe(new Readline({ delimiter: "\n" }));
Related
I am trying to send POST request from a NodeJs script to Python server (running with flask and waitress).
Most of the times the request is failed with the below error.
(node:42790) UnhandledPromiseRejectionWarning: Error: socket hang up
at connResetException (internal/errors.js:639:14)
at TLSSocket.socketOnEnd (_http_client.js:499:23)
at TLSSocket.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1334:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:42790) 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 terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:42790) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I am using NodeJs with axios package to send the request, and the configuration is as given below:
let axiosClient = axios.create({
timeOut: 300000,
maxContentLength: Infinity,
maxBodyLength: Infinity,
httpsAgent: new https.Agent({ keepAlive: true }),
httpAgent: new http.Agent({ keepAlive: true }),
});
let response = await axiosClient.post(end_point_url, data);
And when I checked in the server I could see that the 200 response is being sent, however in the client it is throwing an error.
My expectation is it should be successful in the first try, hence catching the error and retrying may not help in my case as most of the times it fails anyways.
Could you please guide in finding the root cause and fixing the same.
Thank you
let response = await axiosClient.post(end_point_url, data);
You should check end points correctly and use it in try and catch block
My Discord bot keeps returning these errors and I'm not sure how to deal with them since I'm still very new to this whole coding thing.
UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:15) 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 terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 39)
It seems to happen whenever someone attempts to use a command in a Discord channel where my bot cannot send messages.
This is the code I use for a command:
client.on("message", async message => {
if (message.author.bot || message.content.trim() == "") return;
if (message.content.toLowerCase().trim() == "cat") {
const { file } = await fetch("https://aws.random.cat/meow").then(response =>
response.json()
);
return message.channel.send(new $().setColor("RANDOM").setTitle("Your Cat").setImage(file).setFooter('Powered by Catastic'));
}
});
I hope ya'll can help me!
Your bot doesn't have permissions to send a message to the channel the user have written in. Try giving the "Send Messages" permission in that channel using the Permissions menu.
I'm writing a simple voting web api for a class. I'm currently working on PUT and my code is working, but I'm getting a strange error in my command line terminal. Here is the code I'm using to call PUT:
async addVotes(item) {
try {
let response = await axios.put("/api/candidates/" + item._id);
this.getItems();
return true;
}
catch (error) {
console.log(error);
}
console.log(item.name + " is checked");
},
async submitVotes(items) {
for (var item of this.items) {
if (item.selected) {
this.addVotes(item);
}
else {
console.log(item.name + " is not checked");
}
}
},
and here is the PUT code for the api:
app.put('/api/candidates/:id', async(req, res) => {
console.log("initiated put(edit) request");
try {
let candidate = await Candidate.findOne({ _id: req.params.id });
candidate.numVotes += 1;
candidate.save();
res.send(candidate);
res.sendStatus(200);
}
catch (error) {
console.log(error);
res.sendStatus(500);
}
});
I'm getting an error saying this:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:102:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:106:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) 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(). (rejection id: 1)
(node:13246) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
From what I've researched online I'm getting this error because I'm getting more than one response, but I am using async/await so I don't understand why I should be getting that error.
The way you add status to the response is incorrect.
Instead of
res.send(candidate);
res.sendStatus(200);
You should do it this way
res.status(200).send(candidate)
sendStatus sends an 'OK' message on top of setting the status code. You may refer to the Express API reference here https://expressjs.com/en/api.html
The problem is with your PUT API implementation in which you're sending the response twice:
res.send(candidate); // sending json response back to client
res.sendStatus(200); // trying to send response status
So if you're sending a json response then you do not need to send response status explicitly.
res.send(candidate); OR res.json(candidate);
However, if you want to specify the response status then you can do chaining like:
res.status(500).send({ error: "boo" });
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))
});
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.