Skip to content

Commit 02be7a1

Browse files
authored
Merge pull request #166 from rage/catch-java-panic
catch j4rs panics in java plugin
2 parents 819dbb5 + 875601f commit 02be7a1

File tree

2 files changed

+31
-12
lines changed

2 files changed

+31
-12
lines changed

plugins/java/src/error.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@ pub enum JavaError {
2727
#[error("Failed to compile")]
2828
Compilation { stdout: String, stderr: String },
2929

30-
#[error("J4RS error")]
30+
#[error("J4rs error")]
3131
J4rs(#[from] j4rs::errors::J4RsError),
32+
#[error("J4rs panicked: {0}")]
33+
J4rsPanic(String),
3234
#[error(transparent)]
3335
WalkDir(#[from] walkdir::Error),
3436
#[error("JSON error")]

plugins/java/src/lib.rs

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -112,17 +112,34 @@ fn instantiate_jvm() -> Result<Jvm, JavaError> {
112112

113113
let tmc_dir = tmc_dir()?;
114114

115-
let jvm = JvmBuilder::new()
116-
.with_base_path(
117-
tmc_dir
118-
.to_str()
119-
.ok_or_else(|| JavaError::InvalidUtf8Path(tmc_dir.clone()))?,
120-
)
121-
.classpath_entry(junit_runner)
122-
.classpath_entry(checkstyle_runner)
123-
.skip_setting_native_lib()
124-
.java_opt(j4rs::JavaOpt::new("-Dfile.encoding=UTF-8"))
125-
.build()?;
115+
// j4rs may panic
116+
let jvm = match std::panic::catch_unwind(|| -> Result<Jvm, JavaError> {
117+
let jvm = JvmBuilder::new()
118+
.with_base_path(
119+
tmc_dir
120+
.to_str()
121+
.ok_or_else(|| JavaError::InvalidUtf8Path(tmc_dir.clone()))?,
122+
)
123+
.classpath_entry(junit_runner)
124+
.classpath_entry(checkstyle_runner)
125+
.skip_setting_native_lib()
126+
.java_opt(j4rs::JavaOpt::new("-Dfile.encoding=UTF-8"))
127+
.build()?;
128+
Ok(jvm)
129+
}) {
130+
Ok(jvm_result) => jvm_result?,
131+
Err(jvm_panic) => {
132+
// try to extract error message from panic, if any
133+
let error_message = if let Some(string) = jvm_panic.downcast_ref::<&str>() {
134+
string.to_string()
135+
} else if let Ok(string) = jvm_panic.downcast::<String>() {
136+
*string
137+
} else {
138+
"J4rs panicked without an error message".to_string()
139+
};
140+
return Err(JavaError::J4rsPanic(error_message));
141+
}
142+
};
126143

127144
Ok(jvm)
128145
}

0 commit comments

Comments
 (0)