Skip to main content

uni_tmp_jni/wrapper/
errors.rs

1#![allow(missing_docs)]
2
3use thiserror::Error;
4
5use crate::{sys, wrapper::signature::TypeSignature};
6
7pub type Result<T> = std::result::Result<T, Error>;
8
9#[derive(Debug, Error)]
10pub enum Error {
11    #[error("Invalid JValue type cast: {0}. Actual type: {1}")]
12    WrongJValueType(&'static str, &'static str),
13    #[error("Invalid constructor return type (must be void)")]
14    InvalidCtorReturn,
15    #[error("Invalid number of arguments passed to java method: {0}")]
16    InvalidArgList(TypeSignature),
17    #[error("Method not found: {name} {sig}")]
18    MethodNotFound { name: String, sig: String },
19    #[error("Field not found: {name} {sig}")]
20    FieldNotFound { name: String, sig: String },
21    #[error("Java exception was thrown")]
22    JavaException,
23    #[error("JNIEnv null method pointer for {0}")]
24    JNIEnvMethodNotFound(&'static str),
25    #[error("Null pointer in {0}")]
26    NullPtr(&'static str),
27    #[error("Null pointer deref in {0}")]
28    NullDeref(&'static str),
29    #[error("Mutex already locked")]
30    TryLock,
31    #[error("JavaVM null method pointer for {0}")]
32    JavaVMMethodNotFound(&'static str),
33    #[error("Field already set: {0}")]
34    FieldAlreadySet(String),
35    #[error("Throw failed with error code {0}")]
36    ThrowFailed(i32),
37    #[error("Parse failed for input: {1}")]
38    ParseFailed(#[source] combine::error::StringStreamError, String),
39    #[error("JNI call failed")]
40    JniCall(#[source] JniError),
41}
42
43#[derive(Debug, Error)]
44pub enum JniError {
45    #[error("Unknown error")]
46    Unknown,
47    #[error("Current thread is not attached to the Java VM")]
48    ThreadDetached,
49    #[error("JNI version error")]
50    WrongVersion,
51    #[error("Not enough memory")]
52    NoMemory,
53    #[error("VM already created")]
54    AlreadyCreated,
55    #[error("Invalid arguments")]
56    InvalidArguments,
57    #[error("Error code {0}")]
58    Other(sys::jint),
59}
60
61impl<T> From<::std::sync::TryLockError<T>> for Error {
62    fn from(_: ::std::sync::TryLockError<T>) -> Self {
63        Error::TryLock
64    }
65}
66
67pub fn jni_error_code_to_result(code: sys::jint) -> Result<()> {
68    match code {
69        sys::JNI_OK => Ok(()),
70        sys::JNI_ERR => Err(JniError::Unknown),
71        sys::JNI_EDETACHED => Err(JniError::ThreadDetached),
72        sys::JNI_EVERSION => Err(JniError::WrongVersion),
73        sys::JNI_ENOMEM => Err(JniError::NoMemory),
74        sys::JNI_EEXIST => Err(JniError::AlreadyCreated),
75        sys::JNI_EINVAL => Err(JniError::InvalidArguments),
76        _ => Err(JniError::Other(code)),
77    }
78    .map_err(Error::JniCall)
79}
80
81pub struct Exception {
82    pub class: String,
83    pub msg: String,
84}
85
86pub trait ToException {
87    fn to_exception(&self) -> Exception;
88}