MST
星途 面试题库

面试题:Node.js 异步操作中的错误处理及最佳实践

在Node.js中,我们经常会进行异步I/O操作,如文件读取、网络请求等。请详细描述在使用`Promise`、`async/await`进行异步操作时,分别是如何进行错误处理的。同时,阐述如何设计一个通用的错误处理中间件,用于捕获整个应用程序中`async/await`函数抛出的错误,并提供一个简单示例。
30.7万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

使用Promise进行错误处理

Promise中,错误处理通过.catch()方法实现。当Promise被拒绝(即异步操作失败)时,会进入.catch()块。例如:

const fs = require('fs').promises;

fs.readFile('nonexistent.txt', 'utf8')
  .then(data => {
      console.log(data);
    })
  .catch(err => {
      console.error('读取文件错误:', err);
    });

在上述代码中,如果fs.readFile操作失败,Promise会被拒绝,.catch()块会捕获到错误并进行处理。

使用async/await进行错误处理

async/await中,错误处理可以通过try...catch块来实现。await关键字后面的Promise如果被拒绝,会抛出错误,被try...catch捕获。例如:

const fs = require('fs').promises;

async function readFileContent() {
  try {
    const data = await fs.readFile('nonexistent.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error('读取文件错误:', err);
  }
}

readFileContent();

上述代码中,await fs.readFile如果失败,会抛出错误,被try块捕获并在catch块中处理。

设计通用错误处理中间件

在Express应用中,可以设计一个通用的错误处理中间件来捕获async/await函数抛出的错误。示例如下:

const express = require('express');
const app = express();

// 通用错误处理中间件
app.use((err, req, res, next) => {
  console.error('应用程序错误:', err);
  res.status(500).send('服务器内部错误');
});

// 模拟一个异步路由处理函数
app.get('/async', async (req, res, next) => {
  throw new Error('模拟异步错误');
});

const port = 3000;
app.listen(port, () => {
  console.log(`服务器运行在端口 ${port}`);
});

在上述代码中,app.use((err, req, res, next) => {})是通用错误处理中间件,它捕获在路由处理函数(如app.get('/async', async (req, res, next) => {}))中async/await函数抛出的错误,并进行相应处理。这里简单地记录错误并返回500状态码。