Javascript Can';无法从fs.createWriteStream()捕获异常
在我的Electron应用程序的主进程中,我试图处理创建已存在的文件时引发的异常。然而,我的catch子句从未被输入,异常被垃圾邮件发送给用户。我做错了什么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
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();
});