Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't catch exception from fs.createWriteStream()

In the main process of my Electron app, I'm trying to handle an exception thrown when creating a file that already exists. However, my catch clause is never entered, and the exception is spammed to the user. What am I doing wrong?

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???
}
like image 298
Mike Chamberlain Avatar asked Dec 23 '22 19:12

Mike Chamberlain


1 Answers

The correct way to handle this case is by listening to the error event:

const file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
file.on('error', function(err) {
    console.log(err);
    file.end();
});
like image 171
Mike Chamberlain Avatar answered Dec 28 '22 11:12

Mike Chamberlain