在Ubuntu系統中使用Node.js進行開發時,異常捕獲與處理是非常重要的環節。以下是一些常見的異常捕獲與處理方法:
Node.js提供了全局異常捕獲機制,可以捕獲未處理的異常和未捕獲的Promise拒絕。
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
// 可以在這里進行一些清理工作
process.exit(1); // 強制退出進程
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// 可以在這里進行一些清理工作
});
try...catch
捕獲同步異常在同步代碼中,可以使用try...catch
語句來捕獲異常。
try {
// 可能會拋出異常的代碼
const result = riskyOperation();
} catch (err) {
console.error('Caught exception:', err);
}
async/await
和try...catch
捕獲異步異常在使用async/await
時,可以將異步函數放在try...catch
塊中來捕獲異常。
async function asyncFunction() {
try {
const result = await riskyAsyncOperation();
} catch (err) {
console.error('Caught exception:', err);
}
}
如果你在使用Express.js框架,可以使用中間件來捕獲和處理異常。
const express = require('express');
const app = express();
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.get('/', (req, res) => {
throw new Error('Test exception');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
為了更好地管理和分析日志,可以使用一些日志庫,如winston
或pino
。
winston
記錄日志const winston = require('winston');
const logger = winston.createLogger({
level: 'error',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.Console({ format: winston.format.simple() })
]
});
process.on('uncaughtException', (err) => {
logger.error('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
pino
記錄日志const pino = require('pino');
const logger = pino({
level: 'error',
transport: {
target: 'pino-pretty',
options: { colorize: true }
}
});
process.on('uncaughtException', (err) => {
logger.error(err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
logger.error(reason);
});
通過這些方法,你可以在Ubuntu系統中有效地捕獲和處理Node.js應用程序中的異常,確保應用程序的穩定性和可靠性。