init:代码初始化

This commit is contained in:
bai
2026-01-06 09:19:12 +08:00
parent 2dff90de4a
commit ba478d70cc
34 changed files with 11917 additions and 1 deletions

View File

@@ -0,0 +1,74 @@
/**
* 统一错误处理中间件
*/
/**
* 404 错误处理
*/
function notFound(req, res, next) {
const error = new Error(`Not Found - ${req.originalUrl}`);
error.statusCode = 404;
next(error);
}
/**
* 统一错误响应处理
*/
function errorHandler(err, req, res, next) {
// 设置状态码
const statusCode = err.statusCode || 500;
// 开发环境返回详细错误信息,生产环境返回简化信息
const isDevelopment = process.env.NODE_ENV === 'development';
res.status(statusCode).json({
success: false,
message: err.message || '服务器内部错误',
error: isDevelopment ? {
stack: err.stack,
...err
} : undefined,
statusCode
});
// 记录错误日志
if (statusCode >= 500) {
console.error('❌ Server Error:', {
message: err.message,
stack: err.stack,
url: req.originalUrl,
method: req.method,
body: req.body,
query: req.query,
params: req.params
});
}
}
/**
* 异步错误捕获包装器
*/
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
/**
* 自定义错误类
*/
class AppError extends Error {
constructor(message, statusCode = 500) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = {
notFound,
errorHandler,
asyncHandler,
AppError
};