Search code examples
javascriptasync-awaitv8

Handling Exceptions in an Async Javascript function


Building a "Process Orchestration Engine" in C++ as a node add-on. From C++ I call various user-supplied Javascript code snippets, according to a lifecycle. Here is a typical "message_in" method;

async message_in(msg) {
    // Do stuff
    await supervisor->send_message(xxx);
    // Do more stuff
}

My problem is that I want to handle exceptions gracefully, and without the user having to add try catch blocks. Currently if an exception happens in the above method , (In Do stuff), the promise gets set to rejected, and Node moans at me for not handling it.

But on the C++ side I can only "call" the JS Method, I can't see a way to add a catch() handler.

I don't particularly want to use a Global Process handler.

Can anyone think of a way to avoid the Node warnings, as they claim that they will shut down the process for this in future releases.


Solution

  • When a promise is rejected any .catch handlers assigned to that promise are triggered, what you could do:

    async function message_in(msg) {
      await (async () => {
        // Do stuff
        await supervisor->send_message(xxx)
        // Do more stuff
      })().catch((e) => {
          return e; // or do sth sensible with the error
      });
    }

    This does put some bloat into your method, but you can extract that with a function/method decorator (https://www.sitepoint.com/javascript-decorators-what-they-are/)