"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuotaExceededError = exports.BadRequestError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.AppError = void 0;
exports.errorHandler = errorHandler;
async function errorHandler(ctx, next) {
    try {
        await next();
    }
    catch (err) {
        const error = err;
        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.stack = error.stack;
        }
    }
}
// 自定义错误类
class AppError extends Error {
    code;
    status;
    constructor(message, code = 500, status = 500) {
        super(message);
        this.code = code;
        this.status = status;
        this.name = 'AppError';
    }
}
exports.AppError = AppError;
class UnauthorizedError extends AppError {
    constructor(message = '未授权访问') {
        super(message, 401, 401);
    }
}
exports.UnauthorizedError = UnauthorizedError;
class ForbiddenError extends AppError {
    constructor(message = '禁止访问') {
        super(message, 403, 403);
    }
}
exports.ForbiddenError = ForbiddenError;
class NotFoundError extends AppError {
    constructor(message = '资源不存在') {
        super(message, 404, 404);
    }
}
exports.NotFoundError = NotFoundError;
class BadRequestError extends AppError {
    constructor(message = '请求参数错误') {
        super(message, 400, 400);
    }
}
exports.BadRequestError = BadRequestError;
class QuotaExceededError extends AppError {
    constructor(message = '使用次数已达上限') {
        super(message, 429, 429);
    }
}
exports.QuotaExceededError = QuotaExceededError;
