giovanniberti/robusta

Throw an exception specific to the returned error instance

koutheir opened this issue · 0 comments

As far as I understand, the exception class and message are constants for a given fallible method, irrespective of the error that might be returned:

#[call_type(safe(exception_class = "com.example.MyException", message = "Something bad happened"))]
pub extern "jni" fn bar(foo: i32) -> ::robusta_jni::jni::errors::Result<i32> { Ok(foo) }

This is unhelpful to Java callers as it doesn't indicate the reason behind the failure, but only that it failed in a specific native method (information already indicated by the stack trace anyway). The thrown exception has no relationship to the actual error returned.

Instead of the current behavior, I suggest throwing an exception that is based on the error instance itself. If we can assume that the error type implements jni::errors::ToException, then calling jni::errors::ToException::to_exception() on the returned error instance returns a jni::errors::Exception holding enough information to throw an exception object of a specific class and message.

For instance:

use jni::errors::{Exception, ToException};

impl ToException for MyError {
    fn to_exception(&self) -> Exception {
        Exception {
            class: "com/example/MyException".into(),
            msg: self.to_string(),
        }
    }
}