realm-kotlin icon indicating copy to clipboard operation
realm-kotlin copied to clipboard

Streamline exceptions from C++

Open cmelchior opened this issue 3 years ago • 1 comments

I was testing exceptions in some callbacks in JNI.

We have this code in throw_as_java_exception:

jclass error_type_class = (jenv)->FindClass("io/realm/internal/interop/CoreErrorUtils");

Which will crash in FindClass if you have a pending JavaException already, overriding the initial exception (bad!).

I also noticed we have a lot of throw std::runtime_error("An unexpected Error was thrown from Java. See LogCat"); in our code.

This means you have to dig through the logs in order to find the correct message.

The most problematic cases are the ones where C++ calls back through JNI, possible multiple times. In those cases we want C++ to abort as quickly as possible while still maintaining the original error context.

We should look to see if it is possible to somehow get the best of both worlds, which I think would be:

  1. Detect that a Java exception happened
  2. Collect stacktrace.
  3. Wrap it in a C++ exception we can throw which will cancel any C++ code.
  4. Before returning to Java, we unpack the exception and its metadata and convert it back to a Java exception.

cmelchior avatar Feb 04 '22 14:02 cmelchior

We should also rethink how we handle JVM exceptions from native. The current behaviour is to run jni_check_exception right after executing the method. This function will silently clear any pending exceptions, preventing them from reaching the user or the logs. It will prevent the app from hard crashing.

Because of the separation between the user and SDK code, a crash during the execution of such methods means an issue at the SDK/OS level, so once we receive such exceptions we should stop operating with that Realm instance as it might be in an illegal state.

On the other hand, Realm-kotlin on Darwin platform will hard-crash if it encounters an exception when invoking SDK code from core.

We should align the behaviour with Darwin, and even consider some way to capture and propagate these exceptions to user code to allow users to gracefully exit these situations.

clementetb avatar Nov 17 '23 12:11 clementetb