【问题标题】:Can't catch exception from fs.createWriteStream()无法从 fs.createWriteStream() 捕获异常
【发布时间】:2017-04-08 12:10:41
【问题描述】:

在我的 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???
}

【问题讨论】:

  • createWriteStream 不会抛出异常,它会将错误传递给它的异步回调
  • 与其他一些 fs 方法不同,createWriteStream 不接受回调。
  • 是的,没错,它会发出 error 事件,您需要使用回调来处理这些事件(显然,如果没有注册处理程序,它会异步抛出全局异常)。
  • 全局异步异常让我感到困惑。感谢您的澄清。

标签: javascript node.js try-catch electron


【解决方案1】:

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

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

【讨论】:

  • 如果 autoClose 为默认设置,是否需要 file.end() (true)?
【解决方案2】:

我发现的是: https://github.com/electron/electron/issues/2479

我尝试使用纯 Node.js 进行复制,它使用 process.on('uncaughtException', callback) 捕获错误

let desiredPath = '/mnt/c/hello.txt';
let fs = require('fs');

process.on('uncaughtException', function (error) {
    console.log('hello1');
});

try {
  fs.createWriteStream(desiredPath, {
    flags: 'wx',
  });
}
catch (err) {
  console.log('hello');
}

//Output is: 'hello1'

我在 Windows 10 上使用 Ubuntu shell 进行了尝试,在我的情况下,我没有读取该文件的权限,process.on('uncaughtException', callback) 正确捕获它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2021-10-09
    • 2012-01-06
    • 1970-01-01
    相关资源
    最近更新 更多