MST

星途 面试题库

面试题:Node.js 中 try...catch 捕获复杂同步错误场景处理

假设你正在开发一个 Node.js 应用,需要从文件系统中读取一个 JSON 格式的配置文件,解析其中的数据,并根据解析后的数据进行一系列复杂的同步计算(比如多层嵌套对象的遍历和计算)。请使用 try...catch 处理在读取文件、解析 JSON 和计算过程中可能出现的同步错误,并给出合理的错误处理逻辑,例如记录错误日志等。
32.7万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试
const fs = require('fs');
const path = require('path');
const log4js = require('log4js');

// 配置日志记录
log4js.configure({
    appenders: { errorLogger: { type: 'file', filename: 'error.log' } },
    categories: { default: { appenders: ['errorLogger'], level: 'error' } }
});
const logger = log4js.getLogger('errorLogger');

function readAndProcessConfig() {
    try {
        // 读取JSON配置文件
        const configFilePath = path.join(__dirname, 'config.json');
        const data = fs.readFileSync(configFilePath, 'utf8');
        
        // 解析JSON数据
        const config = JSON.parse(data);
        
        // 假设的复杂同步计算函数
        function complexCalculation(obj) {
            let result = 0;
            for (const key in obj) {
                if (typeof obj[key] === 'object') {
                    result += complexCalculation(obj[key]);
                } else if (typeof obj[key] === 'number') {
                    result += obj[key];
                }
            }
            return result;
        }
        
        // 执行复杂计算
        const calculationResult = complexCalculation(config);
        console.log('计算结果:', calculationResult);
    } catch (error) {
        // 错误处理逻辑,记录错误日志
        logger.error('发生错误:', error.message);
        console.error('发生错误:', error.message);
    }
}

readAndProcessConfig();

在上述代码中:

  1. 日志配置:使用 log4js 库来配置错误日志记录到 error.log 文件。
  2. 读取文件:使用 fs.readFileSync 同步读取文件。
  3. 解析JSON:使用 JSON.parse 解析读取到的文件内容。
  4. 复杂计算:假设了一个简单的复杂同步计算函数 complexCalculation 来遍历多层嵌套对象并进行计算。
  5. 错误处理:使用 try...catch 捕获读取文件、解析JSON和计算过程中的错误,并使用日志记录错误信息,同时也在控制台打印错误信息。