Question

I am using an opencv.js Web Assembly build in the browser. The build comes with a JavaScript interface to call the WASM functions but it does not provide any memory management. For example every time I create a new matrix( mat = new cv.Mat() ), to free up the memory taken by that object, I will have to make sure to call the destructor of that object with a delete() method already provided to me by the Opencv interface.


I decided to create an adapter on top of the provided Opencv interface. What I benefit from this is the ability to use other libraries along with Opencv because all the functions in my adapter work with JavaScript arrays and arrayBuffers as opposed to Opencv matrices. Another benefit to using an adapter, is that it makes memory management easier.


Now my problem here is that a lot of errors that are thrown by wasm code are not handled by the provided opencv.js interface and it just raises an exception with a pointer number. I can then use a provided utility function to get a proper error message from the pointer. So ultimately I would have to have a try -catch inside of every function in my adapter to be able to raise proper exception. So my question is, is there a better way to do this or will I have to handle exceptions in every function in my adapter separately.

Was it helpful?

Solution

Pseudo-code because my javascript is rusty.

function translate_exceptions(func, handler)
{
  return function(args...)
  {
    try { return func(args...); }
    catch (ex) { handler(ex); }
  };
};

function realSomeActionB(...) { ... };
function realSomeActionC(...) { ... };

function handleExceptionsByLogging(ex) { ... };
function handleExceptionTranslation(ex) { ... };

return {
   someActionB = translate_exceptions(realSomeActionB, handleExceptionTranslation);
   someActionC = translate_exceptions(realSomeActionC, handleExceptionsByLogging);
};

I use this same trick in C++, and C# all the time. Decorate the function and expose it on the adaptors interface.

You may need several implementations of the wrapper if the language makes it difficult to match function signatures.

Otherwise if the error handling needs to be different pass in a different handler. It may be helpful to implement a handlerChain (calls first handler catchs, calls next etc till the last handler in the chain, or nothing is caught).

Licensed under: CC-BY-SA with attribution
scroll top