Reputation: 1231
I'm getting an Unhandled Rejection error in my code but the trace won't tell me what's causing it. I think it's the webp.cwebp
call that is causing the issue. When I run the code, I successfully convert the image and log status and then run into the Unhandled Rejection. It seems like I don't enter into the last two .then(()
blocks since no console messages get logged from them.
How can I properly handle the rejection error to avoid this error? I've tried inserting and removing status
in the resolve()
and reject()
statements but it doesn't seem to fix it.
// Download image file from Google Cloud Storage bucket.
return file.download({ destination: tempLocalFilename })
.catch((err) => {
console.error('Failed to download file.', err);
return Promise.reject(err);
})
.then(() => {
console.log(`Image ${file.name} has been downloaded to ${tempLocalFilename}.`);
// Convert PNG to webp using webp-converter.
return new Promise( (resolve, reject) => {
webp.cwebp(tempLocalFilename, newLocalFilename, "-q 80", status => {
console.log(status);
if (status === '100') {
resolve();
} else {
reject(status);
}
}
);
});
})
.then(() => {
console.log(`Image ${file.name} has been converted.`);
// Upload the converted image back into the bucket.
return file.bucket.upload(newLocalFilename, { destination: file.name })
.catch((err) => {
console.error('Failed to upload converted image.', err);
return Promise.reject(err);
});
})
.then(() => {
console.log(`Converted image has been uploaded to ${file.name}`);
// Delete the temporary file.
return new Promise((resolve, reject) => {
fs.unlink(tempLocalFilename, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
Upvotes: 8
Views: 36219
Reputation: 19328
Q: I'm getting an Unhandled Rejection error, how can I properly handle the rejection error?
A: Like what the comments already said, a .catch(...)
will stop your exception from bubbling up to become an unhandled rejection error
.
Alternatively you can also insert reject handler function for each of the .then(...)
clause. That is, for each .then()
it should take in 2 functions, one for the happy path and the other for the bad path.
E.g.
return new Promise( (resolve, reject) => {
webp.cwebp(tempLocalFilename, newLocalFilename, "-q 80", status => {
...
}
);
});
})
.then(/*happy path=*/() => {
console.log(`Image ${file.name} has been converted.`);
// Upload the converted image back into the bucket.
return file.bucket.upload(newLocalFilename, { destination: file.name })
.catch((err) => {
console.error('Failed to upload converted image.', err);
return Promise.reject(err);
});
},
/*unhappy path=*/ (error) => {
console.log("oops something went wrong during uploading");
})
/*catch all rejection=*/
.catch(error => {
console.log("something bad happened somewhere, rollback!");
});
Upvotes: 7