# All files / middleware errorHandler.ts

0% Statements 0/53
100% Branches 1/1
100% Functions 1/1
0% Lines 0/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

     import { Context, Next } from 'koa';

    export async function errorHandler(ctx: Context, next: Next): Promise<void> {
      try {
        await next();
      } catch (err: unknown) {
        const error = err as Error & { status?: number; code?: number };

        console.error('❌ Error:', error.message);
        console.error('Stack:', error.stack);

        ctx.status = error.status || 500;
        ctx.body = {
          code: error.code || 500,
          message: error.message || '服务器内部错误',
          data: null,
        };

        // 开发环境返回详细错误
        if (process.env.NODE_ENV === 'development') {
          (ctx.body as Record<string, unknown>).stack = error.stack;
        }
      }
    }

    // 自定义错误类
    export class AppError extends Error {
      public code: number;
      public status: number;

      constructor(message: string, code: number = 500, status: number = 500) {
        super(message);
        this.code = code;
        this.status = status;
        this.name = 'AppError';
      }
    }

    export class UnauthorizedError extends AppError {
      constructor(message: string = '未授权访问') {
        super(message, 401, 401);
      }
    }

    export class ForbiddenError extends AppError {
      constructor(message: string = '禁止访问') {
        super(message, 403, 403);
      }
    }

    export class NotFoundError extends AppError {
      constructor(message: string = '资源不存在') {
        super(message, 404, 404);
      }
    }

    export class BadRequestError extends AppError {
      constructor(message: string = '请求参数错误') {
        super(message, 400, 400);
      }
    }

    export class QuotaExceededError extends AppError {
      constructor(message: string = '使用次数已达上限') {
        super(message, 429, 429);
      }
    }