From c3f7abce5d42818c365e1d9a6c5d07a2b9e14b5f Mon Sep 17 00:00:00 2001 From: SileNce5k Date: Sat, 10 May 2025 15:02:59 +0200 Subject: [PATCH] Tdoss: Improve error handling of downloadImage --- commands/misc/tdoss.js | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/commands/misc/tdoss.js b/commands/misc/tdoss.js index d172ec5..5c80e3a 100644 --- a/commands/misc/tdoss.js +++ b/commands/misc/tdoss.js @@ -44,8 +44,15 @@ module.exports = { } // TODO: Download with correct extension. message.channel.sendTyping(); - if(await this.downloadImage(url, path.resolve(directory, "input.png")) != 0){ - message.channel.send("Something went wrong during the download.\nThe link might be unreachable for the bot or it's not an image.") + let downloadResult = await this.downloadImage(url, path.resolve(directory, "input.png")); + if(downloadResult.value != 0){ + if(downloadResult.value === 3){ + message.channel.send(`Failed to download the provided image, got error '${downloadResult.errorMessage}'`); + }else if (downloadResult.value === 1){ + message.channel.send(`Failed to download the provided image, got response status '${downloadResult.errorMessage}'`); + }else if(downloadResult.value === 2){ + message.channel.send(`The provided url was not an image.`) + } fs.rmSync(`${directory}`, {recursive: true}) return; } @@ -82,14 +89,17 @@ module.exports = { }, // https://stackoverflow.com/a/77210219 async downloadImage(url, path) { - const res = await fetch(url); - if(!res.ok) return 1; - if(!res.headers.get('content-type').startsWith("image")) return 2; + let res = new Response() + try { + res = await fetch(url); + } catch (error) { + return {value: 3, errorMessage: error.cause.message}; + } + if(!res.ok) return {value: 1, errorMessage: res.status.toString()}; + if(!res.headers.get('content-type').startsWith("image")) return {value: 2, errorMessage: ""}; const stream = Readable.fromWeb(res.body) await writeFile(path, stream); - return 0; + return {value: 0, errorMessage: ""}; } } - -