2015-05-22 54 views
0

我在node.js中創建了一個命令行應用程序,它嚴重依賴於節點的文件系統模塊(讀取,更新,創建新文件等)。我爲了相同的目的而編寫了很多功能。根據node.js中的錯誤代碼處理錯誤的錯誤

現在我的問題是:'我能全局捕獲由於任何函數而發生的錯誤嗎?'

例如:

func1(); // throws some error: Cannot find file , errCode:xyz 
func2(); // throws some error: Cannot find file , errCode:xyz 

//some global error catcher  
func(catch errCode:xyz){ 
      console.log("Cannot find file. Make sure file exist and path is correct."); 
    } 

SS

+0

http://stackoverflow.com/questions/205688/javascript-exception-handling可能的重複 –

回答

2

你可以聽https://nodejs.org/api/process.html#process_event_uncaughtexception

process.on('uncaughtException', function handler(err) { 
    // do stuf based on err, but make sure node.js quits after 
    // displaying the error and performing basic cleanup - see below 
}) 

但是不建議這樣做,你肯定不應該讓你的應用程序保持,因爲在此之後運行它可能處於未知狀態。

你的函數應該首先執行一個帶有錯誤的回調,即node-style,並且傳遞迴調的函數應該以正確的方式處理錯誤。