Tdoss: Improve error handling of downloadImage
All checks were successful
CI / CI (push) Successful in 1m22s
All checks were successful
CI / CI (push) Successful in 1m22s
This commit is contained in:
parent
2f371d00ed
commit
c3f7abce5d
1 changed files with 18 additions and 8 deletions
|
@ -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: ""};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue