hn-hlw-service/utils/response.js
2026-07-27 11:28:33 +08:00

86 lines
1.9 KiB
JavaScript
Raw Permalink 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.

const logger = require("./logger");
/**
* 安全发送响应防止重复发送导致的ERR_HTTP_HEADERS_SENT错误
* @param {Object} res - Express响应对象
* @param {*} data - 要发送的数据
* @param {boolean} isJson - 是否以JSON格式发送
* @returns {boolean} - 是否成功发送
*/
function safeSend(res, data, isJson = true) {
if (res.headersSent) {
logger.warn("尝试发送响应但响应头已发送");
return false;
}
try {
if (isJson) {
res.json(data);
} else {
res.send(data);
}
return true;
} catch (error) {
logger.error("发送响应失败:", error);
return false;
}
}
/**
* 发送成功响应
* @param {Object} res - Express响应对象
* @param {*} data - 成功数据
* @param {string} message - 成功消息
*/
function sendSuccess(res, data = null, message = "请求成功") {
return safeSend(res, {
success: true,
message,
data
});
}
/**
* 发送错误响应
* @param {Object} res - Express响应对象
* @param {string} message - 错误消息
* @param {*} error - 错误详情
* @param {number} status - HTTP状态码
*/
function sendError(res, message = "请求失败!", error = null, status = 400) {
if (!res.headersSent) {
res.status(status);
}
return safeSend(res, {
success: false,
message,
error
});
}
/**
* 包装异步路由处理器,自动处理错误
* @param {Function} fn - 异步路由处理函数
* @returns {Function} - 包装后的处理函数
*/
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(error => {
logger.error("异步路由错误:", error);
if (!res.headersSent) {
sendError(res, "服务器内部错误",
error && error.message ? error.message : '',
500
);
}
});
};
}
module.exports = {
safeSend,
sendSuccess,
sendError,
asyncHandler
};