如何捕获Lua Curl的OPT_TIMEOUT超时事件并执行对应操作?
Lua Curl 超时事件捕获实现方案
问题描述
我编写了一段通过Lua Curl请求服务器JSON响应的脚本,通过[curl.OPT_TIMEOUT]设置了2秒超时时间,功能虽生效,但无法捕获超时完成事件,无法在超时时执行打印日志等自定义操作,请问如何实现?
原脚本代码:
local buffer = {} local headers = { "Content-Type: application/json" } url = "https://apiserver/fsapi/json_emcontacts?username=10001&domain=my.domain.com" local c = curl.easy { url = url, ssl_verifypeer = false, ssl_verifyhost = false, httpheader = headers, [curl.OPT_TIMEOUT] = 2, } c:setopt_writefunction(table.insert, buffer) local ok, err = c:perform() if ok then local status = c:getinfo_response_code() if status == 200 then consoleLog("info", "API GET JSON OK\n") local response = json.decode(table.concat(buffer)) consoleLog("info", "Data = "..response['item1'].."\n") else consoleLog("info", "API GET JSON FAIL , status code = "..status.."\n") end else consoleLog("info", "API Call Timeout\n") end
解决方法
lua-curl的perform()方法在请求失败时,第二个返回值err会携带具体错误信息,超时场景下通常会包含"timeout"相关关键词。通过匹配该关键词即可精准捕获超时事件,执行自定义操作。
修改后的脚本:
local buffer = {} local headers = { "Content-Type: application/json" } local url = "https://apiserver/fsapi/json_emcontacts?username=10001&domain=my.domain.com" local c = curl.easy { url = url, ssl_verifypeer = false, ssl_verifyhost = false, httpheader = headers, [curl.OPT_TIMEOUT] = 2, } c:setopt_writefunction(table.insert, buffer) local ok, err = c:perform() if ok then local status = c:getinfo_response_code() if status == 200 then consoleLog("info", "API GET JSON OK\n") local response = json.decode(table.concat(buffer)) consoleLog("info", "Data = "..response['item1'].."\n") else consoleLog("info", "API GET JSON FAIL , status code = "..status.."\n") end else -- 匹配超时错误信息,精准捕获超时事件 if err and string.find(err, "timeout", 1, true) then consoleLog("info", "API Call Timeout: 请求已超时,执行自定义日志记录\n") -- 此处添加你的自定义超时处理逻辑,比如告警、额外日志等 else consoleLog("info", "API Call Failed: " .. (err or "未知错误") .. "\n") end end -- 释放curl资源,避免内存泄漏 c:close()
关键说明
- 错误信息匹配:超时发生时
err会返回类似"Timeout was reached"的信息,通过string.find匹配"timeout"关键词(第三个参数设为true表示精确匹配,不使用正则),即可判断是否为超时事件。 - 资源清理:请求结束后调用
c:close()释放curl句柄,避免长期运行导致内存泄漏。
内容的提问来源于stack exchange,提问作者Ricardo
相关产品推荐
相关产品推荐

