Linux Node.js日志中异常捕获怎么做

Linux Node.js日志中异常捕获怎么做

在Node.js应用中,可以通过try-catch结构实现异常捕捉。在Linux系统中,为了便于调试与监控,通常会将异常信息写入日志文件。以下是一个基础实例,演示了如何在Node.js程序里捕获异常并保存到日志文件中:

  1. 确保已安装Node.js。若未安装,请前往Node.js官网下载并安装。
  2. 建立一个名为app.js的新文件,在其中输入如下代码:

const fs = require('fs');function recordError(error) {  const time = new Date().toISOString();  const logData = `${time}: ${error.stack}n`;  fs.appendFile('error.log', logData, (err) => {    if (err) console.error('Error while writing to log file:', err);  });}try {  // 在此处编写可能引发异常的代码  throw new Error('Example of an error');} catch (error) {  console.error('Error happened:', error.message);  recordError(error);}

登录后复制

文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/682338.html

(0)
上一篇 2025-05-30 12:31
下一篇 2025-05-30 12:35

相关推荐