How to exclude from async function

I have an async function that I expect to throw an exception. However, something is stopping this:

Omitting the catch try blocks, I expect an exception to be thrown that I want to handle outside the function.

The actual result that I get is somewhat confusing:

(node:10636) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): E11000 duplicate key error index.

(node:10636) 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.

async f(obj) {
    await db.collection('...').save(obj);
}

I get the same result when I try to catch an exception and instead another one is imposed instead:

async f(obj) {
    try {
        await db.collection('...').save(obj);
    } catch(e) {
        throw e.message;
    }
}

The function is called from the try block, so you cannot see how this is Unhandled Promise.

I am trying to use fanother function as a parameter:

g(obj, handler) {
    try {
        handler(obj);
    } catch(e);
        ...
    }
}

g(objToSave, f);
+4
source share
3 answers

, , - f g, ( ).

g async, , f. , , , f, , :/p >

async g(obj, handler) {
  return await handler(obj);
}

, handler , ( ).

g () , :

g(objToSave, f).then(...).catch(...)
+6
async f(obj) {
    try {
        await db.collection('...').save(obj);
    } catch(e) {
        throw e.message;
    }
}

try, , Unhandled Promise.

, f(), .save(). :

async f(obj) {
    try {
        await db.collection('...').save(obj);
    } catch(e) {
        console.error(e.message);
    }
}

async- , .

, :

try {
    asyncFunc();
} catch (err) {
    // you have the error here
}

:

asyncFunc().catch(err => {
    // you have the error here
});

, , .

, , - async, .

: async . .

.then() .catch() try { await asyncFunction(); } catch (err) { ... }

, Node Node - . :

+10

This is the only thing you forgot to do. (This is why the warning complains about the raw rejection). Your function is fworking fine.

You cannot throw a synchronous exception from async function, everything is asynchronous, and exceptions lead to the rejection of the promise of the result. This is what you need to catch:

function g(obj, handler) {
    try {
        Promise.resolve(handler(obj)).catch(e => {
            console.error("asynchronous rejection", e);
        });
    } catch(e) {
        console.error("synchronous exception", e);
    }
}
// or just
async function g(obj, handler) {
    try {
        await handler(obj);
//      ^^^^^
    } catch(e) {
        console.error("error", e);
    }
}

g(objToSave, f);
+1
source

Source: https://habr.com/ru/post/1672812/


All Articles