From 10d9874dc645b1780dda119784e77341b6eb7c20 Mon Sep 17 00:00:00 2001 From: _AMD_ Date: Sun, 8 Sep 2024 23:39:27 +0300 Subject: [PATCH] fix: error handling in http_v2.lua when using copas --- lua/http_async.lua | 2 +- lua/http_v2.lua | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/lua/http_async.lua b/lua/http_async.lua index 7b669c3..518b37a 100644 --- a/lua/http_async.lua +++ b/lua/http_async.lua @@ -83,7 +83,7 @@ end -- t headers, s body (for POST), s type, i timeout function http.request(parameters) return copas.addnamedthread("http_request", function(r, b, h) - copas.setErrorHandler(function(msg, co, skt) + copas.seterrorhandler(function(msg, co, skt) if parameters.failed then local suberror = tostring(msg):match("TLS/SSL handshake failed: (.*)$") or tostring(msg) -- closed/System error/{} parameters.failed("copas_error:" .. suberror) -- can be parsed if needed diff --git a/lua/http_v2.lua b/lua/http_v2.lua index e45e939..4ff7790 100644 --- a/lua/http_v2.lua +++ b/lua/http_v2.lua @@ -92,11 +92,20 @@ local function request(reqt) -- reqt.method = reqt.method or "POST" -- PUT, PATCH? end - local ok, code, headers, status = http.request(reqt) - if ok then + -- pcall is to handle copas errors like: TLS/SSL handshake failed: closed or "module 'ssl' not found" + local pcall_ok, http_ok_or_pcall_error, code, headers, status = pcall(http.request, reqt) + if not pcall_ok then + local pcall_error = http_ok_or_pcall_error + -- Однажды попал на /usr/local/share/lua/5.1/copas.lua:70: /usr/local/share/lua/5.1/copas.lua:740: module 'ssl' not found: + -- Не обработал и долго не мог понять почему запрос не делается. Оказалось luasec.. + local suberror = tostring(pcall_error):match("TLS/SSL handshake failed: (.*)$") or tostring(pcall_error) -- closed/System error/{} + reqt.copas_error = "copas_error:" .. suberror -- can be parsed if needed + end + + if pcall_ok and http_ok_or_pcall_error then return table.concat(t), code, headers, status - else - return nil, code + else -- pcall error or http error + return nil, reqt.copas_error or code end end