Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';无法从fs.createWriteStream()捕获异常_Javascript_Node.js_Try Catch_Electron - Fatal编程技术网

Javascript Can';无法从fs.createWriteStream()捕获异常

Javascript Can';无法从fs.createWriteStream()捕获异常,javascript,node.js,try-catch,electron,Javascript,Node.js,Try Catch,Electron,在我的Electron应用程序的主进程中,我试图处理创建已存在的文件时引发的异常。然而,我的catch子句从未被输入,异常被垃圾邮件发送给用户。我做错了什么 let file; try { // this line throws *uncaught* exception if file exists - why??? file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'}); } catch (er

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

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


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

处理此情况的正确方法是监听
错误事件:

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

createWriteStream
不会引发异常,它会将错误传递给其异步回调。与其他一些
fs
方法不同,
createWriteStream
不接受回调。是的,它会发出
error
事件,您需要用回调处理这些事件(显然,如果没有注册处理程序,它会异步抛出一个全局异常)。全局异步异常让我感到困惑。感谢您的澄清。如果autoClose为默认值(true),是否需要file.end()?
const file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
file.on('error', function(err) {
    console.log(err);
    file.end();
});