在Linux環境中,Node.js的錯誤處理主要依賴于錯誤優先回調函數(Error-first Callbacks)和事件監聽。以下是一些建議和最佳實踐:
fs.readFile('file.txt', 'utf8', function(err, data) {
if (err) {
// 處理錯誤
console.error('讀取文件出錯:', err);
return;
}
// 處理數據
console.log('文件內容:', data);
});
on
方法監聽錯誤事件,并在回調函數中處理錯誤。const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('error', function(err) {
console.error('發生錯誤:', err);
});
// 觸發錯誤事件
emitter.emit('error', new Error('示例錯誤'));
try {
const data = fs.readFileSync('file.txt', 'utf8');
console.log('文件內容:', data);
} catch (err) {
console.error('讀取文件出錯:', err);
}
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log('文件內容:', data);
} catch (err) {
console.error('讀取文件出錯:', err);
}
}
readFile();
process.on('uncaughtException')
和process.on('unhandledRejection')
事件來處理未捕獲的異常和Promise拒絕。process.on('uncaughtException', function(err) {
console.error('捕獲到未處理的異常:', err);
});
process.on('unhandledRejection', function(reason, promise) {
console.error('捕獲到未處理的Promise拒絕:', reason);
});
注意:uncaughtException
和unhandledRejection
事件處理程序應謹慎使用,因為它們可能導致應用程序處于不穩定狀態。在生產環境中,建議使用更健壯的錯誤處理和監控機制,如Sentry、PM2等。