/** * R44修复:安全的 JSON 解析工具函数 * * 用途: * 1. 安全解析 JSON 字符串,失败时返回默认值而非抛出异常 * 2. 安全解析 request.json(),提供更友好的错误信息 */ import { NextRequest, NextResponse } from 'next/server' /** * 安全解析 JSON 字符串 * @param jsonString 要解析的 JSON 字符串 * @param fallback 解析失败时的默认值 * @param logError 是否记录错误日志(默认 true) * @returns 解析结果或默认值 */ export function safeJsonParse( jsonString: string, fallback: T, logError: boolean = true ): T { try { return JSON.parse(jsonString) } catch (error) { if (logError) { console.warn('[SafeJSON] JSON 解析失败:', error) } return fallback } } /** * 安全解析 JSON 字符串,返回结果和错误信息 * @param jsonString 要解析的 JSON 字符串 * @returns { data: T | null, error: string | null } */ export function safeJsonParseWithError( jsonString: string ): { data: T | null; error: string | null } { try { const data = JSON.parse(jsonString) as T return { data, error: null } } catch (error) { const errorMessage = error instanceof Error ? error.message : '未知错误' return { data: null, error: `JSON 解析失败: ${errorMessage}` } } } /** * 安全解析请求体 JSON * 如果解析失败,返回错误响应;否则返回解析后的数据 * * @param request NextRequest 对象 * @returns { data: T, response: null } 或 { data: null, response: NextResponse } */ export async function safeParseRequestJson( request: NextRequest ): Promise<{ data: T; response: null } | { data: null; response: NextResponse }> { try { const data = await request.json() as T return { data, response: null } } catch (error) { console.warn('[SafeJSON] 请求体 JSON 解析失败:', error) return { data: null, response: NextResponse.json( { error: '请求数据格式错误,请确保发送的是有效的 JSON' }, { status: 400 } ) } } } /** * 验证并解析请求体 JSON(带类型验证) * * @param request NextRequest 对象 * @param requiredFields 必需的字段列表 * @returns 解析结果或错误响应 */ export async function validateAndParseRequestJson>( request: NextRequest, requiredFields: (keyof T)[] ): Promise<{ data: T; response: null } | { data: null; response: NextResponse }> { // 先解析 JSON const parseResult = await safeParseRequestJson(request) if (parseResult.response) { return parseResult } // 验证必需字段 const data = parseResult.data const missingFields: string[] = [] for (const field of requiredFields) { if (data[field] === undefined || data[field] === null) { missingFields.push(String(field)) } } if (missingFields.length > 0) { return { data: null, response: NextResponse.json( { error: `缺少必需的字段: ${missingFields.join(', ')}` }, { status: 400 } ) } } return { data, response: null } }