Skip to content

Commit b23e2a4

Browse files
committed
Debugging: Add a description of how to handle exceptions.
1 parent 99f6a63 commit b23e2a4

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

site/source/docs/porting/Debugging.rst

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,45 @@ Debug printouts can even execute arbitrary JavaScript. For example::
137137
}
138138

139139

140+
Printing exception messages
141+
===========================
142+
143+
Exceptions are thrown from WebAssembly using exception pointers, which means that try/catch/finally blocks in JavaScript will only receive a number, which represents a pointer into linear memory. In order to get the exception message, the user will need to create some WASM code which will extract the meaning from the exception, for example:
144+
145+
.. code-block:: cpp
146+
147+
#include <bind.h>
148+
149+
std::string getExceptionMessage(int exceptionPtr) {
150+
return std::string(reinterpret_cast<std::exception *>(exceptionPtr)->what());
151+
}
152+
153+
EMSCRIPTEN_BINDINGS(Bindings) {
154+
emscripten::function("getExceptionMessage", &getExceptionMessage);
155+
};
156+
157+
And then handling the exceptions in Javascript will look like this:
158+
159+
.. code-block:: javascript
160+
161+
try {
162+
... // some code that calls WebAssembly
163+
} catch (exception) {
164+
console.error(Module.getExceptionMessage(exception));
165+
} finally {
166+
...
167+
}
168+
169+
It's important to notice that this code will work only for thrown statically allocated exceptions. If your code throws other objects, such as strings or dynamically allocated exceptions, the handling code will need to take that into account. For example, in order to handle thrown strings use:
170+
171+
.. code-block:: javascript
172+
173+
function getExceptionMessage(exception: any): any {
174+
return typeof exception === 'number'
175+
? Module.getExceptionMessage(exception)
176+
: exception;
177+
}
178+
140179
Disabling optimizations
141180
=======================
142181

@@ -285,4 +324,3 @@ Need help?
285324
The :ref:`Emscripten Test Suite <emscripten-test-suite>` contains good examples of almost all functionality offered by Emscripten. If you have a problem, it is a good idea to search the suite to determine whether test code with similar behavior is able to run.
286325

287326
If you've tried the ideas here and you need more help, please :ref:`contact`.
288-

0 commit comments

Comments
 (0)