面试题答案
一键面试使用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状态码。