Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" }));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!