在Ubuntu系统中使用Node.js进行开发时,异常捕获与处理是非常重要的环节。以下是一些常见的异常捕获与处理方法:
1. 全局异常捕获
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); // 可以在这里进行一些清理工作 });
2. 使用try...catch
捕获同步异常
在同步代码中,可以使用try...catch
语句来捕获异常。
try { // 可能会抛出异常的代码 const result = riskyOperation(); } catch (err) { console.error('Caught exception:', err); }
3. 使用async/await
和try...catch
捕获异步异常
在使用async/await
时,可以将异步函数放在try...catch
块中来捕获异常。
async function asyncFunction() { try { const result = await riskyAsyncOperation(); } catch (err) { console.error('Caught exception:', err); } }
4. 使用中间件捕获Express.js中的异常
如果你在使用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'); });
5. 使用日志库记录异常
为了更好地管理和分析日志,可以使用一些日志库,如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应用程序中的异常,确保应用程序的稳定性和可靠性。