Files
api_health/utils/responseUtil.js
T
likandtrae-solo-agent f4760a4c5b fix: 订单与档案接口收敛错误细节与写入校验
internalError 只把通用文案回给前端、详情进日志;状态迁移规则抽到 utils/record_state.js 单点维护;档案更新开 runValidators 并补姓名/手机号/身高体重校验与每人档案上限;已支付订单改为软删除保留审计。
2026-10-24 22:24:39 +08:00

101 lines
2.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import logger from "./logger.js";
/**
* 响应工具类
* 提供统一的响应格式
*
* 约定(与小程序端保持一致):业务状态一律走 body.code,HTTP 状态码固定 200;
* 同时把 code 写进 X-Biz-Code 响应头,便于 nginx/监控按业务码告警而不必解析响应体。
*/
class ResponseUtil {
/**
* 成功响应
* @param {Object} ctx - Koa上下文对象
* @param {Object} data - 响应数据
* @param {string} message - 响应消息
*/
static success(ctx, data, message = '操作成功') {
ctx.status = 200;
ctx.set('X-Biz-Code', '0');
ctx.body = {
code: 0,
msg: message,
data,
ts: Date.now()
};
}
/**
* 错误响应
* @param {Object} ctx - Koa上下文对象
* @param {string} message - 错误消息
* @param {number} errorCode - 应用错误码
*/
static error(ctx, message, data = null, errorCode = 500) {
// 根据规则,只要进入controller,http状态码都是200
ctx.status = 200;
ctx.set('X-Biz-Code', String(errorCode));
ctx.body = {
code: errorCode,
msg: message,
data,
ts: Date.now()
};
}
/**
* 请求参数错误响应
* @param {Object} ctx - Koa上下文对象
* @param {string} message - 错误消息
*/
static badRequest(ctx, message = '请求参数错误', data = null) {
return ResponseUtil.error(ctx, message, data, 400);
}
/**
* 未授权响应
* @param {Object} ctx - Koa上下文对象
* @param {string} message - 错误消息
*/
static unauthorized(ctx, message = '未授权', data = null) {
return ResponseUtil.error(ctx, message, data, 401);
}
/**
* 禁止访问响应
* @param {Object} ctx - Koa上下文对象
* @param {string} message - 错误消息
*/
static forbidden(ctx, message = '禁止访问', data = null) {
return ResponseUtil.error(ctx, message, data, 403);
}
/**
* 资源不存在响应
* @param {Object} ctx - Koa上下文对象
* @param {string} message - 错误消息
*/
static notFound(ctx, message = '资源不存在', data = null) {
return ResponseUtil.error(ctx, message, data, 404);
}
/**
* 服务器内部错误响应
*
* 详细原因只进日志:err.message 可能包含 Mongo 连接串、字段名、堆栈等内部信息,
* 直接回传等于把服务端实现细节暴露给前端/攻击者。
*
* @param {Object} ctx - Koa上下文对象
* @param {string|Error} detail - 内部错误详情(仅用于日志)
* @param {Object} data - 附加数据
*/
static internalError(ctx, detail = null, data = null) {
if (detail) {
const text = detail instanceof Error ? detail.stack : String(detail);
logger.error(`[internal] ${ctx.method} ${ctx.path}: ${text}`);
}
return ResponseUtil.error(ctx, '服务器繁忙,请稍后重试', data, 500);
}
}
export default ResponseUtil;