From 1e06f3c5db2e4b5d998b8f724ad7548b7ba08272 Mon Sep 17 00:00:00 2001 From: siddiqui irshad Date: Tue, 22 Sep 2026 22:25:38 +0530 Subject: [PATCH] fix(utils): prevent unhandled error event and clean up timer on request timeout (fixes #34) --- src/utils.ts | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 082434c..a247fbb 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -110,16 +110,20 @@ export function execute( }; const handleError = (err: Error) => { - reject(err); if (timer) clearTimeout(timer); + reject(err); }; const req = https.get(options, handleResponse).on("error", handleError); if (timeout > 0) { timer = setTimeout(() => { - reject(new RequestTimeoutError()); + if (timer) clearTimeout(timer); + req.off("error", handleError); + req.on("error", () => {}); + const timeoutError = new RequestTimeoutError(); req.destroy(); + reject(timeoutError); }, timeout); } }); @@ -163,6 +167,11 @@ export function uploadImage( return new Promise((resolve, reject) => { let timer: ReturnType; + const handleError = (error: Error) => { + if (timer) clearTimeout(timer); + reject(error); + }; + const req = https.request(options, (resp) => { resp.setEncoding("utf8"); let data = ""; @@ -173,14 +182,16 @@ export function uploadImage( else reject(data); }); }); - req.on("error", (error) => { - if (timer) clearTimeout(timer); - reject(error); - }); + req.on("error", handleError); + if (timeout > 0) { timer = setTimeout(() => { - reject(new RequestTimeoutError()); + if (timer) clearTimeout(timer); + req.off("error", handleError); + req.on("error", () => {}); + const timeoutError = new RequestTimeoutError(); req.destroy(); + reject(timeoutError); }, timeout); } req.end(multipart.body);