2

I feel there should be an easy answer to this I am missing. I rarely get unhandledRejections, however when I do, the reason from process.on('unhandledRejection', (reason, promise) => {...is not always enough to find the origination of the error. So I was hoping to also log information on the [Object Promise] that gets logged from promise.

Code:

module.exports = async (client, process, reason, promise) => {
    const date = new Date();
    const formatDate = stripIndents`${(date.getMonth() + 1)
        .toString().padStart(2, '0')}-${date.getDate()
            .toString().padStart(2, '0')}-${date.getFullYear()
                .toString().padStart(4, '0')}`

    const formatTime = stripIndents`${date.getHours()
        .toString().padStart(2, '0')}-${date.getMinutes()
            .toString().padStart(2, '0')}-${date.getSeconds()
                .toString().padStart(2, '0')}`

    var dir = './logs';

    if (!fs.existsSync(dir)) fs.mkdirSync(dir);

    fs.appendFile(`./logs/${formatDate} UnhandledRejection.log`, `${formatDate} ${formatTime}: A new unhandledRejection: at promise ${promise} for: ${reason}\n`, function (err) {
        if (err) throw err;
        console.log(`A new UnhandledRejection has been logged to: ${formatDate} UnhandledRejection.log`)
    });
}

This of course logs something similar to this in my log file:

09-28-2021 04-00-15: A new unhandledRejection error [object Promise] for TypeError: Volume must be a number. Which in this case, I know I am referring to my volume for my music player, but when I get something like this:

08-10-2021 07-03-02: A new unhandledRejection error [object Promise] for TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters, it can be very hard to find where this problem is coming from.

Although the reason is usually enough to find the origination of the error, gaining access to the [Object Promise], could help further pinpoint the error. I have tried promise.catch(...), promise.then(...), promise.then(...).catch(...), all of which resulted in an infinite console logging loop.

0 Answers0