gpt4 book ai didi

javascript - 无法从 fs.createWriteStream() 捕获异常

转载 作者:行者123 更新时间:2023-11-30 07:33:19 26 4
gpt4 key购买 nike

在我的 Electron 应用程序的主进程中,我试图处理在创建一个已存在的文件时抛出的异常。然而,我的 catch 子句从未被输入,异常被发送给用户。我做错了什么?

let file;
try {
// this line throws *uncaught* exception if file exists - why???
file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
}
catch (err) {
// never gets here - why???
}

最佳答案

处理这种情况的正确方法是监听 error 事件:

const file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
file.on('error', function(err) {
console.log(err);
file.end();
});

关于javascript - 无法从 fs.createWriteStream() 捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43293921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com