答案:Web服务器应通过统一异常处理中间件捕获各类错误,使用结构化错误对象(如AppError)携带状态码和消息,结合专业日志库(如winston)记录详细信息,并区分环境返回客户端友好提示,确保系统稳定与可维护性。

当Web服务器遇到异常时,良好的错误处理和日志记录机制能帮助开发者快速定位问题、提升系统稳定性。以下是一个实用的异常处理与日志记录示例,适用于常见的Web应用环境(如Node.js + Express)。
Web服务器可能遇到多种异常:
针对这些情况,需在中间件中统一拦截并处理。
在Express中,可通过错误处理中间件捕获异步和同步异常:
app.use((err, req, res, next) => {
// 默认状态码
const statusCode = err.statusCode || 500;
<p>// 记录错误日志
console.error(<code>${new Date().toISOString()} - ${req.method} ${req.url}</code>);
console.error(<code>状态码: ${statusCode}</code>);
console.error(<code>错误信息: ${err.message}</code>);
console.error(<code>堆栈: ${err.stack}</code>);</p><p>// 返回客户端友好的响应
res.status(statusCode).json({
success: false,
message: statusCode === 500 ? '服务器内部错误' : err.message
});
});</p>这个中间件应放在所有路由之后注册,确保能捕获后续中间件抛出的错误。
避免直接抛出字符串错误,建议封装错误对象:
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
Error.captureStackTrace(this, this.constructor);
}
}
<p>// 在业务逻辑中使用
if (!user) {
throw new AppError('用户不存在', 404);
}</p>这样能保证错误携带状态码和可读信息,便于日志记录和响应生成。
生产环境中不应仅依赖console.error,推荐使用专业日志库如winston或pino:
const winston = require('winston');
<p>const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' })
]
});</p><p>// 在异常处理中使用
logger.error({
timestamp: new Date().toISOString(),
method: req.method,
url: req.url,
statusCode: err.statusCode || 500,
message: err.message,
stack: err.stack
});</p>结构化日志有助于后期检索与分析,尤其在分布式系统中至关重要。
基本上就这些。关键在于统一处理入口、结构化错误对象、持久化记录日志,并区分开发与生产环境的反馈信息。不复杂但容易忽略细节。
以上就是Web服务器异常处理与日志记录示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号