Eurydice
Eurydice

Reputation: 8439

how to solve UnhandledPromiseRejectionWarning?

I recently learnt javascript and I have trouble with understanding the Promise concept. Here is a snippet for which I would expect an exception to occur.

async function testRepository(): Promise<void> {
    throw new Error('error');
};

async function testService(): Promise<void> {
    try {
        return await testRepository();
    } catch (err) {
        throw err;
    }
};

async function testController(): Promise<void> {
    try {
        return await testService();
    } catch (err) {
        throw err;
    }
}

(async () => {
    try {
        console.log(await testController());
    } catch (err) {
        throw err;
    }
})();

When running tat code, I get the following error message:

(node:16670) UnhandledPromiseRejectionWarning: Error: error
    at /home/pellegrini/temp/webservices/test.js:42:19
    at step (/home/pellegrini/temp/webservices/test.js:33:23)
    at Object.next (/home/pellegrini/temp/webservices/test.js:14:53)
    at /home/pellegrini/temp/webservices/test.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (/home/pellegrini/temp/webservices/test.js:4:12)
    at testRepository (/home/pellegrini/temp/webservices/test.js:40:12)
    at /home/pellegrini/temp/webservices/test.js:54:42
    at step (/home/pellegrini/temp/webservices/test.js:33:23)
    at Object.next (/home/pellegrini/temp/webservices/test.js:14:53)
(node:16670) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:16670) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Could you tell me what is wrong with that code and to make it work. By working I mean generating an Error as I would expect if I understand right the concept of Promise.

Upvotes: 0

Views: 263

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85161

The issue is that you keep re-throwing the error, and don't ever handle it anywhere. So it bubbles out and out and out, until it generates an UnhandledPromiseRejectionWarning.

You just need to break this chain at some point, by handling the error. For example:

async function testService(): Promise<void> {
    try {
        return await testRepository();
    } catch (err) {
        console.log('got an error');
        //throw err; // Don't re-throw
    }
};

Upvotes: 1

Related Questions