74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
// server/utils/createApiResponse.ts - 统一封装后端接口成功/失败响应,并把内部异常转换为安全前端文案。
|
|
import type { ICommonResponse } from "#shared/types";
|
|
|
|
const INTERNAL_SERVER_ERROR_MESSAGE = "服务器内部错误";
|
|
|
|
/**
|
|
* 构造统一成功响应。
|
|
*
|
|
* @param data 要返回给前端的数据,没有数据时传 null
|
|
* @param msg 提示信息,默认“请求成功”
|
|
* @returns 符合 ICommonResponse 格式的对象,code 固定为 0
|
|
*/
|
|
export const createSuccessResponse = <T>(
|
|
data: T | null = null,
|
|
msg: string = "请求成功"
|
|
): ICommonResponse<T> => {
|
|
return {
|
|
code: 0,
|
|
data,
|
|
msg
|
|
};
|
|
};
|
|
|
|
/**
|
|
* 构造统一错误响应。
|
|
*
|
|
* @param code 错误码,默认 400;上游错误时传上游状态码
|
|
* @param msg 错误描述,展示给前端的提示文案
|
|
* @param data 附带的错误详情,通常是上游返回的原始响应体
|
|
* @returns 符合 ICommonResponse 格式的错误响应
|
|
*/
|
|
export const createErrorResponse = (
|
|
code: number = 400,
|
|
msg: string = "请求失败",
|
|
data: unknown = null
|
|
): ICommonResponse => {
|
|
return {
|
|
code,
|
|
data,
|
|
msg
|
|
};
|
|
};
|
|
|
|
/**
|
|
* 将上游或内部异常转换为统一响应。
|
|
*
|
|
* 调用方必须先在服务端日志中记录 error。这里永远不把上游 message、响应体、
|
|
* statusMessage 或 data 返回给前端,避免暴露内部服务、供应商、token 使用细节。
|
|
*/
|
|
export const createUpstreamErrorResponse = (
|
|
error: unknown,
|
|
_fallbackMessage: string = INTERNAL_SERVER_ERROR_MESSAGE
|
|
): ICommonResponse => {
|
|
void error;
|
|
return createErrorResponse(500, INTERNAL_SERVER_ERROR_MESSAGE);
|
|
};
|
|
|
|
/** 判断上游或本地鉴权错误是否为 401,用于统一清理失效登录态 */
|
|
export const isUnauthorizedError = (error: unknown): boolean => {
|
|
const fetchError = error as {
|
|
response?: {
|
|
status?: number;
|
|
};
|
|
status?: number;
|
|
statusCode?: number;
|
|
};
|
|
|
|
return (
|
|
fetchError.statusCode === 401 ||
|
|
fetchError.status === 401 ||
|
|
fetchError.response?.status === 401
|
|
);
|
|
};
|