2017-04-08 279 views
0

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

回答

2

來處理這種情況的正確方法是通過聽取error事件:

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

什麼我發現是: 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)可以正確捕獲該文件。