Implementé un servicio de back-end muy minimalista usando expressjs y socket.io para transferir lecturas de datos en serie desde un arduino a un front-end de reacción. Uso el paquete SerialPort para lograr esto. mi problema es cuando intento conectarme a un puerto serie que no está disponible o no está conectado, la biblioteca SerialPort arroja el siguiente 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)este error es completamente aceptable y esperado porque estoy tratando de conectarme a un dispositivo que no existe. pero quiero manejar este error muy bien y notificar al frente que la conexión del puerto serie falló. para lograr esto, utilicé un bloque try catch como el siguiente.
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"); } }); });pero cuando se lanza el error, este bloque catch no se ejecutará. ¿Qué puedo hacer para solucionar este problema? ¿Cómo puedo manejar este error?
En lugar de un bloque try-catch, use el evento de error:
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" }));