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. // TODO: Download with correct extension.
message.channel.sendTyping(); message.channel.sendTyping();
if(await this.downloadImage(url, path.resolve(directory, "input.png")) != 0){ let downloadResult = await this.downloadImage(url, path.resolve(directory, "input.png"));
message.channel.send("Something went wrong during the download.\nThe link might be unreachable for the bot or it's not an image.") 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}) fs.rmSync(`${directory}`, {recursive: true})
return; return;
} }
@ -82,14 +89,17 @@ module.exports = {
}, },
// https://stackoverflow.com/a/77210219 // https://stackoverflow.com/a/77210219
async downloadImage(url, path) { async downloadImage(url, path) {
const res = await fetch(url); let res = new Response()
if(!res.ok) return 1; try {
if(!res.headers.get('content-type').startsWith("image")) return 2; 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) const stream = Readable.fromWeb(res.body)
await writeFile(path, stream); await writeFile(path, stream);
return 0; return {value: 0, errorMessage: ""};
} }
} }