catching exceptions in Javascript thrown from ActiveX control written in C++

南楼画角 提交于 2019-12-11 01:56:09

问题


I've written an ActiveX control in C++ that throws (C++) exceptions out when error conditions occur within the control. The Javascript code that invokes the object representing an instance of the control is surrounded by a try - catch block:

try
{
    var controlInstance = window.controlInstance;

    ... perform operations on controlInstance ...
}
catch (e)
{
    alert("something bad happened");
}

Now, when I run this code under IE8 (or 7 or 6) with a Visual Studio (2008) debugger attached to it, everything works as expected - whether the control is compiled with or without DEBUG on. However, when running the browser without a debugger attached, IE crashes (really) when an exception crosses the boundary between the control and JScript.

Does anyone have any suggestions around how to solve this problem? I realize that I can change the control's interface to pass the exception back as an argument but I really would rather not make such a change.

Any help would be appreciated.


回答1:


You need AtlReportError. It throws javascript exception with description string:

STDMETHODIMP CMyCtrl::MyMethod()
{
   ...
   if (bSucceeded)
      return S_OK;
   else
      // hRes is set to DISP_E_EXCEPTION
      return AtlReportError (GetObjectCLSID(), "My error message");
}



回答2:


You can't pass C++ exceptions to the script - you need to catch the C++ exceptions in Invoke()/InvokeEx(), translate them and pass them out using the EXCEPINFO* parameter.

E.g. excerpting from FireBreath's implementation:

HRESULT YourIDispatchExImpl::InvokeEx(DISPID id, LCID lcid, WORD wFlags, 
                                      DISPPARAMS *pdp, VARIANT *pvarRes, 
                                      EXCEPINFO *pei, IServiceProvider *pspCaller)
{
    try {
        // do actual work
    } catch (const cppException& e) {
        if (pei != NULL) {
            pei->bstrSource = CComBSTR(ACTIVEX_PROGID);
            pei->bstrDescription = CComBSTR(e.what());
            // ...
        }
        return DISP_E_EXCEPTION;
    }

    // ...



回答3:


How are you passing the exception from C++? A general throw does not work if you want to propagate your exception to javascript. You need to throw exception of type COleDispatchException and the right way to do is calling

AfxThrowOleDispatchException(101, _T("Exception Text Here")); // First parameter is exception code. 

Reference: http://doc.sumy.ua/prog/active_x/ch03.htm#Heading20



来源:https://stackoverflow.com/questions/3791687/catching-exceptions-in-javascript-thrown-from-activex-control-written-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!