无法捕捉异常fs.createWriteStream()

问题描述:

在我的Electron应用程序的主要过程中,我试图处理创建已存在的文件时引发的异常。但是,我的catch子句从不输入,并且该例外被垃圾邮件给用户。我究竟做错了什么?无法捕捉异常fs.createWriteStream()

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??? 
} 
+0

'createWriteStream'不抛出异常,它传递一个错误的*异步回调*。 – Bergi

+0

与其他'fs'方法不同,'createWriteStream'不接受回调。 –

+1

是的,它会发出你需要用回调处理的错误事件(显然,如果没有注册处理程序,它会异步抛出全局异常)。 – Bergi

来处理这种情况的正确方法是通过听取error事件:

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

什么我发现是: 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' 

我与Ubuntu试图抓到错误壳牌Windows 10,在我的情况下,我没有权限读取该文件,并且process.on('uncaughtException', callback)可以正确捕获该文件。