在 Linux 環境下使用 Node.js 進行錯誤處理,可以遵循以下幾個步驟:
try {
// 你的代碼
} catch (error) {
// 錯誤處理
}
const fs = require('fs');
const readStream = fs.createReadStream('file.txt');
readStream.on('error', (error) => {
// 錯誤處理
});
async function readFile() {
try {
const data = await fs.promises.readFile('file.txt', 'utf-8');
// 處理數據
} catch (error) {
// 錯誤處理
}
}
readFile();
fs.readFile('file.txt', 'utf-8', (error, data) => {
if (error) {
// 錯誤處理
} else {
// 處理數據
}
});
process.on('uncaughtException', (error) => {
// 錯誤處理
});
process.on('unhandledRejection', (reason, promise) => {
// 錯誤處理
});
請注意,全局錯誤處理主要用于捕獲那些無法通過其他方式捕獲的錯誤。在生產環境中,建議使用更健壯的錯誤處理機制,例如使用日志記錄錯誤并發送通知。