在Node.js中,可以使用中间件来捕获和处理异常请求。以下是一个使用Express框架的示例,展示了如何识别和记录异常请求:
npm install express morgan
app.js的文件,并添加以下代码:const express = require('express');
const morgan = require('morgan');
const app = express();
// 自定义Morgan日志格式,包含状态码和响应时间
morgan.token('status', (req, res) => {
return res.statusCode;
});
morgan.token('response-time', (req, res) => {
return res.get('X-Response-Time');
});
app.use(morgan(':method :url :status :response-time ms - :res[content-length]'));
// 示例路由
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/error', (req, res) => {
// 抛出一个异常
throw new Error('Oops! Something went wrong.');
});
// 异常处理中间件
app.use((err, req, res, next) => {
console.error('Exception caught:', err.message);
res.status(500).send('Internal Server Error');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
在这个示例中,我们自定义了Morgan日志格式,以包含状态码和响应时间。我们还添加了一个异常处理中间件,用于捕获和处理应用程序中的异常。
当访问/error路由时,应用程序会抛出一个异常,异常处理中间件会捕获该异常并记录相关信息。同时,客户端会收到一个500 Internal Server Error响应。
要运行此示例,请在终端中执行以下命令:
node app.js
然后访问http://localhost:3000/error,查看异常请求的记录。