简体   繁体   English

如何正确处理 express js 错误?

[英]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.我已经使用 expressjs 和 socket.io 实现了一个非常简约的后端服务,以将串行数据读数从 arduino 传输到反应前端。 i use SerialPort package to achieve this.我使用 SerialPort package 来实现这一点。 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.我的问题是当我尝试连接到不可用或未连接的串行端口时,SerialPort 库会抛出以下错误。

(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.为了实现这一点,我使用了一个 try catch 块,如下所示。

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.但是当抛出错误时,这个 catch 块将不会运行。 what can i do to fix this issue?我能做些什么来解决这个问题? how can i handle this error?我该如何处理这个错误?

Instead of a try-catch-block, use the error event:而不是 try-catch-block,使用错误事件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM