我已經使用 expressjs 和 socket.io 實作了一個非常簡約的后端服務,以將串行資料讀數從 arduino 傳輸到反應前端。我使用 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 塊將不會運行。我能做些什么來解決這個問題?我該如何處理這個錯誤?
uj5u.com熱心網友回復:
而不是 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" }));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406425.html
標籤:
