File size: 1,742 Bytes
d47b053
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**

 * Error Handler Middleware

 * Express 错误处理中间件

 */

import type { Request, Response, NextFunction } from 'express'
import { formatError, getStatusCode, isOperationalError } from '../utils/errors'
import { logger } from '../utils/logger'

/**

 * 错误处理中间件

 */
export function errorHandler(

  error: any,

  req: Request,

  res: Response,

  next: NextFunction

): void {
  // 记录错误日志
  const statusCode = getStatusCode(error)
  const isOperational = isOperationalError(error)

  if (isOperational) {
    // 操作性错误(预期错误)- INFO 级别
    logger.info('Operational error occurred', {
      method: req.method,
      path: req.path,
      statusCode,
      error: error.message,
      stack: error.stack
    })
  } else {
    // 编程错误(未预期错误)- ERROR 级别
    logger.error('Programming error occurred', {
      method: req.method,
      path: req.path,
      statusCode,
      error: error.message,
      stack: error.stack
    })
  }

  // 格式化错误响应
  const errorResponse = formatError(error)

  // 发送错误响应
  res.status(statusCode).json(errorResponse)
}

/**

 * 404 未找到处理中间件

 */
export function notFoundHandler(

  req: Request,

  res: Response,

  next: NextFunction

): void {
  res.status(404).json({
    error: 'Route not found',
    path: req.path,
    method: req.method
  })
}

/**

 * 异步路由错误捕获包装器

 */
export function asyncHandler(

  fn: (req: Request, res: Response, next: NextFunction) => Promise<any>

) {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next)
  }
}