Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bindings/java): convey backtrace on exception #3286

Merged
merged 3 commits into from
Oct 15, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions bindings/java/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,34 @@
// specific language governing permissions and limitations
// under the License.

use std::backtrace::{Backtrace, BacktraceStatus};
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;

use jni::objects::JThrowable;
use jni::objects::JValue;
use jni::JNIEnv;

use opendal::ErrorKind;

pub(crate) struct Error {
inner: opendal::Error,
backtrace: Backtrace,
}

impl Error {
pub(crate) fn unexpected(err: impl Into<anyhow::Error> + Display) -> Error {
pub(crate) fn new(inner: opendal::Error) -> Error {
Error {
inner: opendal::Error::new(ErrorKind::Unexpected, &err.to_string()).set_source(err),
inner,
backtrace: Backtrace::capture(),
}
}

pub(crate) fn unexpected(err: impl Into<anyhow::Error> + Display) -> Error {
tisonkun marked this conversation as resolved.
Show resolved Hide resolved
Self::new(opendal::Error::new(ErrorKind::Unexpected, &err.to_string()).set_source(err))
}

pub(crate) fn throw(&self, env: &mut JNIEnv) {
if let Err(err) = self.do_throw(env) {
match err {
Expand Down Expand Up @@ -68,7 +76,8 @@ impl Error {
ErrorKind::InvalidInput => "InvalidInput",
_ => "Unexpected",
})?;
let message = env.new_string(self.inner.to_string())?;

let message = env.new_string(self.to_string())?;
let exception = env.new_object(
class,
"(Ljava/lang/String;Ljava/lang/String;)V",
Expand All @@ -85,7 +94,7 @@ impl Error {

impl From<opendal::Error> for Error {
fn from(error: opendal::Error) -> Self {
Self { inner: error }
Self::new(error)
}
}

Expand Down Expand Up @@ -115,7 +124,13 @@ impl Debug for Error {

impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.inner, f)
Display::fmt(&self.inner, f)?;
if self.backtrace.status() == BacktraceStatus::Captured {
tisonkun marked this conversation as resolved.
Show resolved Hide resolved
writeln!(f)?;
writeln!(f, "Backtrace:")?;
writeln!(f, "{}", self.backtrace)?;
}
Ok(())
}
}

Expand Down
Loading