ryskajakub
ryskajakub

Reputation: 6431

handle exception in javascript

consider this code:

async function outer() {
    const inner = async () => {
        throw "xxx";
    };
    inner();
}
async function f() {
    try {
        await outer();
    }
    catch (error) {
        console.log(error);
    }
}
f();

when I run the code with node: node myfile.js, I will get this exception:

node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "xxx".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

How can I modify the f function, so it will actually handle the exception? I specifically don't want to modify outer as this is blackbox code for me and I don't want to attach some global handler. What I want to achieve is to just modify the f so it actually handles the exception. Is that possible?

node --version
v15.14.0

Upvotes: 0

Views: 140

Answers (1)

Quentin
Quentin

Reputation: 943556

The promise created by inner isn't tied, in any way, to the promise created by outer. outer will resolve before the promise created by inner does.

You need to await it.

async function outer() {
    const inner = async () => {
        throw "xxx";
    };
    await inner();
}
async function f() {
    try {
        await outer();
    }
    catch (error) {
        console.log(error);
    }
}
f();

I specifically don't want to modify outer as this is blackbox code for me

It is the only way. You can't fix a bug in outer without changing outer.

Upvotes: 2

Related Questions