Tdoss: Improve error handling of downloadImage
All checks were successful
CI / CI (push) Successful in 1m22s

This commit is contained in:
SileNce5k 2025-05-10 15:02:59 +02:00
parent 2f371d00ed
commit c3f7abce5d
Signed by: SileNce
GPG key ID: B0A142BB4291B204

View file

@ -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: ""};
}
}