0

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.

2 Answers 2

1

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/)

Sign up to request clarification or add additional context in comments.

7 Comments

My problem is that I want to deal with an exception that occurs before the await call. So, in the line // Do stuff. That seems to cause node to look for a catch handler attached to the message_in method, and , of course, there isn't one.
Ok, got it - I've updated my answer to reflect this, it would be probably best to create a decorator for using this in the long run.
It solves my problem, thanks! However what I would really like to return in the case of an error is a Rejected promise. Do you know how I might do that?
in the catch statement you can return an explicitly rejected promise, so: return Promise.reject(e).
Unfortunately, when I do that, I am back to Node complaining about an UnhandledPromiseRejectedWarning - chicken and egg :-(
|
0

You can attach the handler quite easily:

Local<Value> res;
TryCatch try_catch(isolate);
if (fn->Call(...).ToLocal(&res)) {
  if (res->IsPromise()) {
    res.As<Promise>()->Catch(context, errorHandlerFunction);
  }
} else {
  // check try_catch
}

1 Comment

The Node error appears in the fn->Call processing, so it seems that it's already too late to attach the handler after return from the Call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.