Search code examples
javascriptnode.jsexpresssocket.ionode-serialport

how to handle express js errors properly?


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 ?


Solution

  • 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" }));