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

status: add error source in more cases #762

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
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
34 changes: 32 additions & 2 deletions tonic/src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,11 @@ impl Status {
#[cfg_attr(not(feature = "transport"), allow(dead_code))]
pub(crate) fn from_error(err: Box<dyn Error + Send + Sync + 'static>) -> Status {
Status::try_from_error(err)
.unwrap_or_else(|err| Status::new(Code::Unknown, err.to_string()))
.unwrap_or_else(|err| {
let mut status = Status::new(Code::Unknown, err.to_string());
status.source = Some(err);
status
})
}

pub(crate) fn try_from_error(
Expand Down Expand Up @@ -628,7 +632,9 @@ impl From<std::io::Error> for Status {
ErrorKind::UnexpectedEof => Code::OutOfRange,
_ => Code::Unknown,
};
Status::new(code, err.to_string())
let mut status = Status::new(code, err.to_string());
status.source = Some(Box::new(err));
status
}
}

Expand Down Expand Up @@ -801,6 +807,8 @@ impl From<Code> for i32 {

#[cfg(test)]
mod tests {
use std::io;

use super::*;
use crate::Error;

Expand Down Expand Up @@ -830,11 +838,33 @@ mod tests {

#[test]
fn from_error_unknown() {
use std::error::Error as _;

let orig: Error = "peek-a-boo".into();
let found = Status::from_error(orig);

assert_eq!(found.code(), Code::Unknown);
assert_eq!(found.message(), "peek-a-boo".to_string());
assert_eq!(found.source().unwrap().to_string(), "peek-a-boo");
}

#[test]
fn from_error_io() {
use std::error::Error as _;

let orig: Error = "in-use".into();
let io_orig = io::Error::new(io::ErrorKind::AddrInUse, orig);
let found: Status = io_orig.into();

assert_eq!(found.code(), Code::Unavailable);
assert_eq!(found.message(), "in-use".to_string());

let source = found
.source()
.and_then(|err| err.downcast_ref::<io::Error>())
.unwrap();
assert_eq!(source.to_string(), "in-use");
assert_eq!(source.kind(), io::ErrorKind::AddrInUse);
}

#[test]
Expand Down