面试题答案
一键面试在Node.js应用程序中,可以通过process.on('uncaughtException')
来全局捕获未捕获的异常。以下是具体示例:
- 捕获未捕获异常并记录日志:
const fs = require('fs');
const path = require('path');
process.on('uncaughtException', (err) => {
const logPath = path.join(__dirname, 'error.log');
const errorMessage = `Uncaught Exception: ${err.message}\n${err.stack}`;
fs.appendFile(logPath, errorMessage + '\n', (err) => {
if (err) {
console.error('Error writing to log file:', err);
}
});
console.error('Uncaught Exception:', err.message);
console.error(err.stack);
});
// 模拟一个未捕获异常
throw new Error('This is an uncaught exception');
- 捕获未捕获异常并进行适当错误响应(以HTTP服务器为例):
const http = require('http');
const server = http.createServer((req, res) => {
// 模拟一个未捕获异常
throw new Error('This is an uncaught exception in HTTP server');
res.end('Hello World');
});
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err.message);
console.error(err.stack);
// 假设这是一个HTTP服务器,向客户端返回错误响应
server.close(() => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
});
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
在上述示例中,process.on('uncaughtException')
捕获到异常后,第一个例子将异常信息记录到日志文件并打印到控制台;第二个例子在捕获到异常后关闭HTTP服务器,并向客户端返回一个500错误响应。 这样可以优雅地处理未捕获的异常,避免应用程序崩溃并提供有用的错误信息。