debug: 保存请求体到文件并打印错误位置上下文

改进:
- 保存每次请求体到 /tmp/last_request_body.json
- 解析错误时提取错误位置(character N)
- 打印错误位置前后各 100 字符
- 返回错误位置给前端

方便调试 Unicode 转义问题。
This commit is contained in:
2026-08-15 18:27:59 +08:00
parent 1d601c172a
commit 9a8914e90e
+19 -1
View File
@@ -160,18 +160,36 @@ http {
-- 记录请求体大小,方便调试
ngx.log(ngx.INFO, "Received body size: ", string.len(body))
-- 调试:保存请求体到文件以便分析
local debug_file = io.open("/tmp/last_request_body.json", "w")
if debug_file then
debug_file:write(body)
debug_file:close()
ngx.log(ngx.INFO, "Request body saved to /tmp/last_request_body.json")
end
-- 解析 JSON
local ok, data = pcall(cjson.decode, body)
if not ok then
-- 记录解析错误的详细信息
ngx.log(ngx.ERR, "JSON parse error: ", data)
ngx.log(ngx.ERR, "Body preview (first 500 chars): ", string.sub(body, 1, 500))
-- 保存出错的位置附近的内容
local error_pos = tonumber(string.match(tostring(data), "character (%d+)"))
if error_pos then
local start_pos = math.max(1, error_pos - 100)
local end_pos = math.min(string.len(body), error_pos + 100)
ngx.log(ngx.ERR, "Error context (chars ", start_pos, "-", end_pos, "): ", string.sub(body, start_pos, end_pos))
end
ngx.status = 400
ngx.say(cjson.encode({
error = "Invalid JSON",
details = tostring(data),
body_size = string.len(body),
body_preview = string.sub(body, 1, 200)
body_preview = string.sub(body, 1, 200),
error_position = error_pos
}))
return
end