【问题标题】:how to handle express js errors properly?如何正确处理 express js 错误?
【发布时间】:2022-01-08 15:51:22
【问题描述】:

我已经使用 expressjs 和 socket.io 实现了一个非常简约的后端服务,以将串行数据读数从 arduino 传输到 react 前端。我使用 SerialPort 包来实现这一点。我的问题是当我尝试连接到不可用或未连接的串行端口时,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)

这个错误是完全可以接受和预期的,因为我正在尝试连接到一个不存在的设备。但我想很好地处理这个错误并通知前端串行端口连接失败。为了实现这一点,我使用了如下所示的 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");
    }
  });
});

但是当错误被抛出时,这个 catch 块将不会运行。我能做些什么来解决这个问题?我该如何处理这个错误?

【问题讨论】:

  • 你试过socket.on('error', function)吗?

标签: javascript node.js express socket.io node-serialport


【解决方案1】:

使用错误事件代替 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" }));

【讨论】:

  • 感谢您指出我正确的方向,我最终使用了 port.on('error', function(err) { console.log('Error: ', err.message) })
猜你喜欢
  • 2011-12-04
  • 1970-01-01
  • 2017-03-07
  • 2012-05-24
  • 2016-04-07
  • 1970-01-01
  • 2018-12-06
  • 2012-12-28
  • 2010-10-11
相关资源
最近更新 更多