ubuntu

Ubuntu Node.js日志中异常捕获与处理方法

小樊
45
2025-04-05 00:47:15
栏目: 编程语言

在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/awaittry...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. 使用日志库记录异常

为了更好地管理和分析日志,可以使用一些日志库,如winstonpino

使用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应用程序中的异常,确保应用程序的稳定性和可靠性。

0
看了该问题的人还看了