javascriptexceptionasynchronousasync-await

How to handle unexpected errors thrown inside an async function?


Let's say there's an async function that has an implementation bug, for example:

function resolveAfter2Seconds() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(undefined_variable);
        }, 2000);
    });
}

How can I call this function and handle the ReferenceError it will throw?

I've tried using a .catch block as follows:

resolveAfter2Seconds().then(result => console.log(result)).catch(error => console.log(error));

And also a wrapper function like so:

async function safeAsyncCall() {
    try {
        return await resolveAfter2Seconds()
    } catch {
        console.log("Something went wrong")
    }
}

safeAsyncCall().then(result => console.log(result))

Neither of which work (the code still crashes with a ReferenceError).

How can I safely call this function?


Solution

  • I know that this isn't what you want to hear, but I don't think there's any safe way to call that function. It's just broken code.

    You can work around it like KLASANGUI suggested in his answer but I personally would rather fix it.

    If this library is installed via npm, i.e in your node_modules, I would edit it from within node_modules and use patch-package or yarn patch. This will generate a patch file from your changes which can then be applied each time npm install is run using something like postinstall.

    As someone who's dealt with a lot of broken js packages, this is what I would do. I don't like having to do weird hacks in my own code because of someone else's broken code.