视图字符串传递给抛出异常的构造函数

时间:2015-11-15 16:11:13

标签: javascript c++ exception emscripten

我正在尝试调试使用Emscripten编译的C ++程序,该程序会抛出异常,特别是runtime_error,它将字符串作为what_arg传递。但是,当它们抛出时,我只是在Javascript控制台中得到一个数字(指针值?)输出。传递给构造函数的字符串会更有帮助。

例如,程序

#include <stdexcept>

int main()
{
  throw std::runtime_error("I want to see this in the console");
  return 0;
}

使用Emscripten 1.35.0 64bit(在Mac OS X上)通过命令

编译
em++ exception.cc -o exception.html

在浏览器中查看时,输出到控制台

Uncaught 5247024

我怎样才能在运行时看到what_arg参数是什么?

理想情况下,这将在C ++代码中没有try-catch块,因此我可以使用DISABLE_EXCEPTION_CATCHING标志。有一些方法可以使用Pointer_stringify将C风格字符串的内存地址转换为Javascript字符串。也许作为例外传递的数字有类似的东西?

2 个答案:

答案 0 :(得分:1)

您需要catch并手动打印what()字符串。

编辑:此在C ++中使用try / catch块完成,例如:

int main(int argc, char** argv)
{
    try
    {
        throw std::runtime_error("I want to see this in the console");
    }
    catch (const std::runtime_error& error)
    {
        std::cout << error.what() << std::endl;
    }

    return 0;
}

答案 1 :(得分:0)

有一种使用window.onerror的方法,当出现未处理的异常时,似乎会调用它。使用这个,我可以

  • 获取onerror处理程序的第5个参数
  • 如果不是数字
  • ,则不执行任何操作
  • 使用例如ccall
  • 将数字传回C ++世界中的函数
  • 然后该函数对数字执行reinterpret_cast以获取指向runtime_error的指针
  • 致电what上的runtime_error并将结果字符串传递给cerr

执行此操作的示例C ++程序是

#include <stdexcept>
#include <iostream>

#include <emscripten.h>

extern "C" void EMSCRIPTEN_KEEPALIVE what_to_stderr(intptr_t pointer)
{
  auto error = reinterpret_cast<std::runtime_error *>(pointer);
  std::cerr << error->what() << "\n";
}

int main()
{
  throw std::runtime_error("I want to see this in the console");
  return 0;
}

可以使用命令

编译
em++ -std=c++11 exception.cc -o exception.js

并在简单的HTML页面中运行

<!doctype html>
<html>
  <head>
    <title>Exception test</title>
    <script>
      var Module = {};
      window.onerror = function(message, url, line, column, e) {
        if (typeof e != 'number') return;
        var pointer = e;
        Module.ccall('what_to_stderr', 'number', ['number'], [pointer]);
      }
    </script>
    <script src="exception.js"></script>
  </head>
  <body>
  </body>
</html>

它似乎适用于Chrome 46和Firefox 41。