Stack Overflow Asked by Joel Imbergamo on December 9, 2021
So I’m working on connecting an arduino with my computer using Node.js and when the arduino is connected everything works fine, but when is not it obviously throws an error(Error: Opening COM6: File not found) but I’m unable to catch it with a try catch block, it’s important for my program to continue running even if the arduino isn’t connected so I need to handle the error. Here is my code:
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
class Arduino{
connect(port, baudRate = 9600, autoOpen = true){
this.portName = port;
this.baudRate = baudRate;
try{
this.port = new SerialPort(port, { baudRate: baudRate, autoOpen: autoOpen } );
}catch(error) {
console.log(err);
}
this.parser = this.port.pipe(new Readline({ delimiter: 'rn' }));
}
var arduino = new Arduino();
arduino.connect("COM6", 9600);
Here is the hole error:
UnhandledPromiseRejectionWarning: Error: Opening COM6: File not found
(node:12884)
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)
(node:12884) [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.
Any idea of how to catch the error?
Thank you in advance!
Ok, I found the answer, you need to create an event receiver of the port on the event 'error':
this.port.on('error', function(err){
console.log("error ----> " + err);
})
This handles the error fine!
Answered by Joel Imbergamo on December 9, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP