Skip to content

Commit

Permalink
Revamp errors in aws-smithy-types-convert
Browse files Browse the repository at this point in the history
  • Loading branch information
jdisanti committed Oct 29, 2022
1 parent 170daaf commit 55d4ceb
Showing 1 changed file with 33 additions and 14 deletions.
47 changes: 33 additions & 14 deletions rust-runtime/aws-smithy-types-convert/src/date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,33 @@ use aws_smithy_types::DateTime;
use std::error::Error as StdError;
use std::fmt;

/// Conversion error
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
enum ErrorKind {
/// Conversion failed because the value being converted is out of range for its destination
#[non_exhaustive]
OutOfRange(Box<dyn StdError + Send + Sync + 'static>),
}

impl StdError for Error {}
/// Conversion error
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
}

impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match &self.kind {
ErrorKind::OutOfRange(source) => Some(source.as_ref() as _),
}
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfRange(cause) => {
match self.kind {
ErrorKind::OutOfRange(_) => {
write!(
f,
"conversion failed because the value is out of range for its destination: {}",
cause
"conversion failed because the value is out of range for its destination",
)
}
}
Expand Down Expand Up @@ -132,8 +140,9 @@ impl DateTimeExt for DateTime {

#[cfg(feature = "convert-time")]
fn to_time(&self) -> Result<time::OffsetDateTime, Error> {
time::OffsetDateTime::from_unix_timestamp_nanos(self.as_nanos())
.map_err(|err| Error::OutOfRange(err.into()))
time::OffsetDateTime::from_unix_timestamp_nanos(self.as_nanos()).map_err(|err| Error {
kind: ErrorKind::OutOfRange(err.into()),
})
}

#[cfg(feature = "convert-time")]
Expand All @@ -149,7 +158,7 @@ mod test {
use aws_smithy_types::date_time::{DateTime, Format};

#[cfg(feature = "convert-time")]
use super::Error;
use super::{Error, ErrorKind};

#[test]
#[cfg(feature = "convert-chrono")]
Expand Down Expand Up @@ -230,8 +239,18 @@ mod test {
assert_eq!(expected, date_time.to_time().unwrap());

let date_time = DateTime::from_secs_and_nanos(i64::MAX, 0);
assert!(matches!(date_time.to_time(), Err(Error::OutOfRange(_))));
assert!(matches!(
date_time.to_time(),
Err(Error {
kind: ErrorKind::OutOfRange(_)
})
));
let date_time = DateTime::from_secs_and_nanos(i64::MIN, 0);
assert!(matches!(date_time.to_time(), Err(Error::OutOfRange(_))));
assert!(matches!(
date_time.to_time(),
Err(Error {
kind: ErrorKind::OutOfRange(_)
})
));
}
}

0 comments on commit 55d4ceb

Please sign in to comment.