locked
Catch JavaScript Exception in C++

    Question

  • The Setting

    In an async operation in a C++ WinRT component, I call a JavaScript function and wait for its completion like this:

    auto callbackTask = concurrency::create_task(
      dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, 
        ref new Windows::UI::Core::DispatchedHandler([callback]() {
          callback();
        })
      )
    );
    callbackTask.get();

    I got the dispatcher using CoreWindow::GetForCurrentThread()->Dispatcher before the async operation was started. callback is a public delegate void EachCallback(Platform::String^).

    The Problem

    When the called JavaScript function throws an exception (throw new Error('Some Error')), the native debugger with first-chance exceptions enabled tells me that a Js::JavascriptExceptionObject was thrown on the callback() line. However, I can't find a way to catch it. A try/catch-block around callback() for Platform::Object^ or std::exception doesn't catch anything. I don't know where Js::JavascriptExceptionObject is defined, so I can't catch it directly. Even catch (...) didn't catch anything.

    So, what is the correct way and place to catch a JavaScript exception in C++? Or is it possible at all?



    • Edited by gdoo Thursday, July 19, 2012 12:29 PM
    Thursday, July 19, 2012 12:26 PM

Answers

  • Hi,

    From my experience, in general this is not a recommended approach. You can catch an exception thrown in the (C++) component on the (JavaScript) consumer side, but not the reverse. It is common for a component to throw meaningful unhandled exceptions. But if an exception is thrown on the consumer side, then it is the consumer’s responsibility to handle it. So please try to use the JavaScript code handles the exception, and gracefully terminate the C++ component. Your component is needed to perform validation. For example, if the consumer is not properly written, and an invalid input is passed to your component due to unhandled exceptions, your component need to validate the input and throw a meaningful exception.

    Best Regards,

    Ming Xu.


    Please mark the replies as answers if they help or unmark if not.
    If you have any feedback about my replies, please contact msdnmg@microsoft.com.
    Microsoft One Code Framework

    Monday, July 23, 2012 4:25 PM
    Moderator