use std::fmt;
use std::ops::RangeInclusive;
use std::path::PathBuf;
use aws_sdk_s3::operation::abort_multipart_upload::AbortMultipartUploadError;
use aws_sdk_s3::operation::complete_multipart_upload::CompleteMultipartUploadError;
use aws_sdk_s3::operation::create_multipart_upload::CreateMultipartUploadError;
use aws_sdk_s3::operation::get_object::GetObjectError;
use aws_sdk_s3::operation::head_object::HeadObjectError;
use aws_sdk_s3::operation::list_objects_v2::ListObjectsV2Error;
use aws_sdk_s3::operation::put_object::PutObjectError;
use aws_sdk_s3::operation::upload_part::UploadPartError;
use aws_sdk_s3::operation::RequestIdExt;
use aws_smithy_observability::unit_of_work::checksums::{
ChecksumOutcome, ResponseChecksumAlgorithm,
};
use aws_smithy_runtime_api::client::orchestrator::HttpResponse;
use aws_smithy_runtime_api::client::result::{ConnectorError, SdkError};
use aws_smithy_types::error::metadata::ProvideErrorMetadata;
use aws_smithy_types::retry::ErrorKind as RetryErrorKind;
use aws_types::request_id::RequestId;
use crate::model::ChecksumAlgorithm;
use crate::types::{FailedDownload, FailedUpload};
pub use crate::model::UnknownVariantError;
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
source: BoxError,
extra: Option<Box<ErrorExtra>>,
}
#[derive(Debug, Default)]
struct ErrorExtra {
service: Option<ServiceMetadata>,
http_status: Option<u16>,
location: Option<ChunkRef>,
local: Option<LocalContext>,
upload_id: Option<String>,
failed_uploads: Option<Vec<FailedUpload>>,
failed_downloads: Option<Vec<FailedDownload>>,
transient_transport: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
InputInvalid,
IOError,
RuntimeError,
ObjectNotDiscoverable,
ServiceError,
IntegrityError(IntegrityError),
ChildOperationFailed,
OperationCancelled,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct IntegrityError {
algorithm: Option<ChecksumAlgorithm>,
expected: Option<String>,
computed: Option<String>,
}
impl IntegrityError {
pub fn algorithm(&self) -> Option<&ChecksumAlgorithm> {
self.algorithm.as_ref()
}
pub fn expected(&self) -> Option<&str> {
self.expected.as_deref()
}
pub fn computed(&self) -> Option<&str> {
self.computed.as_deref()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct ChunkRef {
seq: u64,
range: Option<RangeInclusive<u64>>,
}
impl ChunkRef {
pub(crate) fn new(seq: u64, range: Option<RangeInclusive<u64>>) -> Self {
Self { seq, range }
}
pub fn seq(&self) -> u64 {
self.seq
}
pub fn byte_range(&self) -> Option<&RangeInclusive<u64>> {
self.range.as_ref()
}
}
#[derive(Debug)]
struct LocalContext {
action: &'static str,
path: PathBuf,
key: Option<String>,
}
#[derive(Debug)]
struct ServiceMetadata {
operation: &'static str,
code: Option<String>,
message: Option<String>,
request_id: Option<String>,
extended_request_id: Option<String>,
}
impl Error {
pub fn new<E>(kind: ErrorKind, err: E) -> Error
where
E: Into<BoxError>,
{
Error {
kind,
source: err.into(),
extra: None,
}
}
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
#[cfg(test)]
pub(crate) fn test_transient_transport() -> Error {
Error {
kind: ErrorKind::ServiceError,
source: "injected transient transport".into(),
extra: Some(Box::new(ErrorExtra {
transient_transport: true,
..Default::default()
})),
}
}
#[cfg(test)]
pub(crate) fn test_service_error(code: &str) -> Error {
Error {
kind: ErrorKind::ServiceError,
source: "injected service error".into(),
extra: Some(Box::new(ErrorExtra {
service: Some(ServiceMetadata {
operation: "TestOperation",
code: Some(code.to_owned()),
message: None,
request_id: None,
extended_request_id: None,
}),
..Default::default()
})),
}
}
fn service(&self) -> Option<&ServiceMetadata> {
self.extra.as_ref().and_then(|e| e.service.as_ref())
}
fn extra_mut(&mut self) -> &mut ErrorExtra {
self.extra
.get_or_insert_with(|| Box::new(ErrorExtra::default()))
}
pub fn operation_name(&self) -> Option<&str> {
self.service().map(|m| m.operation)
}
pub fn code(&self) -> Option<&str> {
self.service().and_then(|m| m.code.as_deref())
}
pub(crate) fn http_status(&self) -> Option<u16> {
self.extra.as_ref().and_then(|e| e.http_status)
}
pub fn message(&self) -> Option<&str> {
self.service().and_then(|m| m.message.as_deref())
}
pub fn request_id(&self) -> Option<&str> {
self.service().and_then(|m| m.request_id.as_deref())
}
pub fn extended_request_id(&self) -> Option<&str> {
self.service()
.and_then(|m| m.extended_request_id.as_deref())
}
pub fn is_not_found(&self) -> bool {
matches!(
self.code(),
Some("NotFound" | "NoSuchKey" | "NoSuchUpload" | "NoSuchBucket")
)
}
pub(crate) fn is_transient_transport(&self) -> bool {
self.extra.as_ref().is_some_and(|e| e.transient_transport)
}
pub fn chunk(&self) -> Option<&ChunkRef> {
self.extra.as_ref().and_then(|e| e.location.as_ref())
}
pub fn upload_id(&self) -> Option<&str> {
self.extra.as_ref().and_then(|e| e.upload_id.as_deref())
}
pub fn failed_uploads(&self) -> Option<&[FailedUpload]> {
self.extra
.as_ref()
.and_then(|e| e.failed_uploads.as_deref())
}
pub fn failed_downloads(&self) -> Option<&[FailedDownload]> {
self.extra
.as_ref()
.and_then(|e| e.failed_downloads.as_deref())
}
pub(crate) fn with_chunk(mut self, location: ChunkRef) -> Self {
self.extra_mut().location = Some(location);
self
}
pub(crate) fn with_local(mut self, action: &'static str, path: impl Into<PathBuf>) -> Self {
self.extra_mut().local = Some(LocalContext {
action,
path: path.into(),
key: None,
});
self
}
pub(crate) fn with_local_key(mut self, key: impl Into<String>) -> Self {
if let Some(local) = self.extra.as_mut().and_then(|e| e.local.as_mut()) {
local.key = Some(key.into());
}
self
}
pub(crate) fn with_upload_id(mut self, upload_id: String) -> Self {
self.extra_mut().upload_id = Some(upload_id);
self
}
pub(crate) fn with_failed_uploads(mut self, failed: Vec<FailedUpload>) -> Self {
self.extra_mut().failed_uploads = Some(failed);
self
}
pub(crate) fn with_failed_downloads(mut self, failed: Vec<FailedDownload>) -> Self {
self.extra_mut().failed_downloads = Some(failed);
self
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
ErrorKind::InputInvalid => write!(f, "invalid input")?,
ErrorKind::IOError => write!(f, "I/O error")?,
ErrorKind::RuntimeError => write!(f, "runtime error")?,
ErrorKind::ObjectNotDiscoverable => write!(f, "object discovery failed")?,
ErrorKind::ChildOperationFailed => {
write!(f, "child operation failed")?;
let first_and_count = self
.failed_uploads()
.map(|f| {
let id = f
.first()
.and_then(|u| u.source_path())
.map(|p| p.display().to_string());
(id, f.len())
})
.or_else(|| {
self.failed_downloads().map(|f| {
let id = f.first().and_then(|d| d.input().key()).map(str::to_owned);
(id, f.len())
})
});
if let Some((id, n)) = first_and_count {
match id {
Some(id) => write!(f, ": {id}")?,
None => write!(f, ": 1 object")?,
}
if n > 1 {
write!(f, " (and {} more)", n - 1)?;
}
}
}
ErrorKind::OperationCancelled => write!(f, "operation cancelled")?,
ErrorKind::ServiceError => {
write!(f, "service error")?;
if let Some(m) = self.service() {
write!(f, " calling {}", m.operation)?;
if let Some(c) = &m.code {
write!(f, " ({c})")?;
}
}
}
ErrorKind::IntegrityError(ie) => {
write!(f, "integrity error")?;
if let Some(a) = &ie.algorithm {
write!(f, " ({a})")?;
}
}
}
if let Some(local) = self.extra.as_ref().and_then(|e| e.local.as_ref()) {
write!(f, " {} \"{}\"", local.action, local.path.display())?;
if let Some(key) = &local.key {
write!(f, " (key \"{key}\")")?;
}
}
if let Some(loc) = self.chunk() {
match &loc.range {
Some(r) => write!(f, " [chunk {}, bytes {}-{}]", loc.seq, r.start(), r.end())?,
None => write!(f, " [chunk {}]", loc.seq)?,
}
}
if let Some(m) = self.service() {
match (&m.request_id, &m.extended_request_id) {
(Some(rid), Some(ext)) => {
write!(f, " (request id: {rid}, extended request id: {ext})")?
}
(Some(rid), None) => write!(f, " (request id: {rid})")?,
_ => {}
}
}
Ok(())
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
if matches!(self.kind, ErrorKind::ChildOperationFailed) {
let first_child = self
.failed_uploads()
.and_then(<[FailedUpload]>::first)
.map(FailedUpload::error)
.or_else(|| {
self.failed_downloads()
.and_then(<[FailedDownload]>::first)
.map(FailedDownload::error)
});
if let Some(child) = first_child {
return Some(child);
}
}
Some(self.source.as_ref())
}
}
impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
Self::new(ErrorKind::IOError, value)
}
}
impl From<aws_smithy_types::error::operation::BuildError> for Error {
fn from(value: aws_smithy_types::error::operation::BuildError) -> Self {
Self::new(ErrorKind::InputInvalid, value)
}
}
pub(crate) fn invalid_input<E>(err: E) -> Error
where
E: Into<BoxError>,
{
Error::new(ErrorKind::InputInvalid, err)
}
pub(crate) fn io_at(action: &'static str, path: impl Into<PathBuf>, err: std::io::Error) -> Error {
Error::new(ErrorKind::IOError, err).with_local(action, path)
}
pub(crate) fn discovery_failed<E>(err: E) -> Error
where
E: Into<BoxError>,
{
Error::new(ErrorKind::ObjectNotDiscoverable, err)
}
pub(crate) fn from_kind<E>(kind: ErrorKind) -> impl FnOnce(E) -> Error
where
E: Into<BoxError>,
{
|err| Error::new(kind, err)
}
pub(crate) fn body_read_error<E>(err: E, checksum: Option<ChecksumOutcome>) -> Error
where
E: Into<BoxError>,
{
match checksum {
Some(ChecksumOutcome::Mismatch {
algorithm,
expected,
computed,
}) => Error {
kind: ErrorKind::IntegrityError(IntegrityError {
algorithm: Some(checksum_algorithm(algorithm)),
expected: Some(expected),
computed: Some(computed),
}),
source: err.into(),
extra: None,
},
_ => Error::new(ErrorKind::IOError, err),
}
}
pub(crate) fn integrity_mismatch(
algorithm: ChecksumAlgorithm,
expected: String,
computed: String,
) -> Error {
Error::new(
ErrorKind::IntegrityError(IntegrityError {
algorithm: Some(algorithm),
expected: Some(expected),
computed: Some(computed),
}),
"calculated object checksum does not match its stored value",
)
}
pub(crate) fn checksum_algorithm(algorithm: ResponseChecksumAlgorithm) -> ChecksumAlgorithm {
ChecksumAlgorithm::from(algorithm.as_str().to_ascii_uppercase().as_str())
}
fn service_metadata<E, R>(operation: &'static str, e: &SdkError<E, R>) -> ServiceMetadata
where
E: ProvideErrorMetadata,
SdkError<E, R>: RequestId + RequestIdExt,
{
ServiceMetadata {
operation,
code: e.code().map(str::to_owned),
message: e.message().map(str::to_owned),
request_id: e.request_id().map(str::to_owned),
extended_request_id: e.extended_request_id().map(str::to_owned),
}
}
fn connector_error_is_transient(conn: &ConnectorError) -> bool {
conn.is_io() || conn.is_timeout() || conn.as_other() == Some(RetryErrorKind::TransientError)
}
fn is_sdk_transient_transport<E, R>(e: &SdkError<E, R>) -> bool {
if let SdkError::TimeoutError(_) = e {
return true;
}
let conn = match e {
SdkError::DispatchFailure(df) => df.as_connector_error(),
_ => return false,
};
let Some(conn) = conn else { return false };
if connector_error_is_transient(conn) {
return true;
}
let mut source = std::error::Error::source(conn);
while let Some(err) = source {
if let Some(conn) = err.downcast_ref::<ConnectorError>() {
if connector_error_is_transient(conn) {
return true;
}
}
source = err.source();
}
false
}
pub(crate) trait SdkOperationError:
ProvideErrorMetadata + std::error::Error + Send + Sync + 'static
{
const OPERATION_NAME: &'static str;
}
pub(crate) fn service_error<E: SdkOperationError>(e: SdkError<E, HttpResponse>) -> Error {
let service = service_metadata(E::OPERATION_NAME, &e);
let http_status = e.raw_response().map(|response| response.status().as_u16());
let transient_transport = is_sdk_transient_transport(&e);
Error {
kind: ErrorKind::ServiceError,
source: Box::new(e),
extra: Some(Box::new(ErrorExtra {
service: Some(service),
http_status,
transient_transport,
..Default::default()
})),
}
}
pub(crate) fn head_object_error(e: SdkError<HeadObjectError, HttpResponse>) -> Error {
let mut error = service_error(e);
let code = error
.extra
.as_ref()
.and_then(|extra| extra.http_status)
.and_then(head_status_code);
if let (Some(code), Some(service)) = (
code,
error
.extra
.as_mut()
.and_then(|extra| extra.service.as_mut()),
) {
service.code.get_or_insert_with(|| code.to_owned());
}
error
}
fn head_status_code(status: u16) -> Option<&'static str> {
match status {
304 => Some("NotModified"),
412 => Some("PreconditionFailed"),
416 => Some("InvalidRange"),
_ => None,
}
}
pub(crate) fn invalid_service_response<O>(
operation: &'static str,
output: &O,
message: impl Into<String>,
) -> Error
where
O: RequestId + RequestIdExt,
{
invalid_service_response_ids(
operation,
output.request_id(),
output.extended_request_id(),
message,
)
}
pub(crate) fn invalid_service_response_ids(
operation: &'static str,
request_id: Option<&str>,
extended_request_id: Option<&str>,
message: impl Into<String>,
) -> Error {
let message = message.into();
Error {
kind: ErrorKind::ServiceError,
source: message.clone().into(),
extra: Some(Box::new(ErrorExtra {
service: Some(ServiceMetadata {
operation,
code: None,
message: Some(message),
request_id: request_id.map(str::to_owned),
extended_request_id: extended_request_id.map(str::to_owned),
}),
..Default::default()
})),
}
}
macro_rules! sdk_operation_error {
($err:ty, $op:literal) => {
impl SdkOperationError for $err {
const OPERATION_NAME: &'static str = $op;
}
};
}
sdk_operation_error!(GetObjectError, "GetObject");
sdk_operation_error!(HeadObjectError, "HeadObject");
sdk_operation_error!(PutObjectError, "PutObject");
sdk_operation_error!(UploadPartError, "UploadPart");
sdk_operation_error!(CreateMultipartUploadError, "CreateMultipartUpload");
sdk_operation_error!(CompleteMultipartUploadError, "CompleteMultipartUpload");
sdk_operation_error!(AbortMultipartUploadError, "AbortMultipartUpload");
sdk_operation_error!(ListObjectsV2Error, "ListObjectsV2");
impl From<crate::io::walk::WalkError> for Error {
fn from(e: crate::io::walk::WalkError) -> Self {
use crate::io::walk::WalkErrorKind;
let path = e.path().map(std::path::Path::to_path_buf);
let local = |err: Error| match path {
Some(path) => err.with_local("walking", path),
None => err,
};
match e.kind() {
WalkErrorKind::Service => {
match e
.into_source()
.downcast::<SdkError<ListObjectsV2Error, HttpResponse>>()
{
Ok(sdk) => service_error(*sdk),
Err(src) => Error::new(ErrorKind::ObjectNotDiscoverable, src),
}
}
WalkErrorKind::SourceUnreadable | WalkErrorKind::NotADirectory => {
local(Error::new(ErrorKind::InputInvalid, e))
}
WalkErrorKind::Io
| WalkErrorKind::PermissionDenied
| WalkErrorKind::BrokenSymlink
| WalkErrorKind::SymlinkCycle => local(Error::new(ErrorKind::IOError, e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn service(
operation: &'static str,
code: Option<&str>,
request_id: Option<&str>,
extended_request_id: Option<&str>,
) -> Error {
Error {
kind: ErrorKind::ServiceError,
source: "boom".into(),
extra: Some(Box::new(ErrorExtra {
service: Some(ServiceMetadata {
operation,
code: code.map(str::to_owned),
message: Some("the message".to_owned()),
request_id: request_id.map(str::to_owned),
extended_request_id: extended_request_id.map(str::to_owned),
}),
..Default::default()
})),
}
}
#[test]
fn display_plain_kind() {
let e = Error::new(ErrorKind::OperationCancelled, "x");
assert_eq!(e.to_string(), "operation cancelled");
}
#[test]
fn body_read_error_classifies_mismatch_from_checksum_outcome() {
let outcome = ChecksumOutcome::Mismatch {
algorithm: ResponseChecksumAlgorithm::Crc32,
expected: "AAAAAA==".to_owned(),
computed: "BBBBBB==".to_owned(),
};
let e = body_read_error("opaque body error", Some(outcome));
let ErrorKind::IntegrityError(ie) = e.kind() else {
panic!("expected IntegrityError, got {:?}", e.kind());
};
assert_eq!(ie.algorithm(), Some(&ChecksumAlgorithm::Crc32));
assert_eq!(ie.expected(), Some("AAAAAA=="));
assert_eq!(ie.computed(), Some("BBBBBB=="));
}
#[test]
fn checksum_algorithm_maps_each_known_name() {
for (algorithm, expected) in [
(ResponseChecksumAlgorithm::Crc32, ChecksumAlgorithm::Crc32),
(ResponseChecksumAlgorithm::Crc32c, ChecksumAlgorithm::Crc32C),
(
ResponseChecksumAlgorithm::Crc64Nvme,
ChecksumAlgorithm::Crc64Nvme,
),
(ResponseChecksumAlgorithm::Sha1, ChecksumAlgorithm::Sha1),
(ResponseChecksumAlgorithm::Sha256, ChecksumAlgorithm::Sha256),
] {
assert_eq!(checksum_algorithm(algorithm), expected);
}
}
#[test]
fn display_service_error_full() {
let e = service(
"GetObject",
Some("NoSuchKey"),
Some("REQ123"),
Some("EXT456"),
);
assert_eq!(
e.to_string(),
"service error calling GetObject (NoSuchKey) (request id: REQ123, extended request id: EXT456)"
);
}
#[test]
fn display_service_error_request_id_only() {
let e = service("PutObject", Some("AccessDenied"), Some("REQ123"), None);
assert_eq!(
e.to_string(),
"service error calling PutObject (AccessDenied) (request id: REQ123)"
);
}
#[test]
fn display_service_error_no_metadata() {
let e = service("HeadObject", None, None, None);
assert_eq!(e.to_string(), "service error calling HeadObject");
}
#[test]
fn display_omits_source_message() {
let e = service("GetObject", Some("NoSuchKey"), None, None);
assert!(!e.to_string().contains("the message"));
}
#[test]
fn display_integrity_error() {
let e = Error {
kind: ErrorKind::IntegrityError(IntegrityError {
algorithm: Some(ChecksumAlgorithm::Crc32),
expected: Some("AAAA".to_owned()),
computed: Some("BBBB".to_owned()),
}),
source: "mismatch".into(),
extra: None,
};
assert_eq!(e.to_string(), "integrity error (CRC32)");
}
#[test]
fn display_with_chunk() {
let e = Error::new(ErrorKind::IOError, "x").with_chunk(ChunkRef::new(3, Some(0..=1023)));
assert_eq!(e.to_string(), "I/O error [chunk 3, bytes 0-1023]");
}
#[test]
fn display_chunk_no_range() {
let e = Error::new(ErrorKind::IOError, "x").with_chunk(ChunkRef::new(7, None));
assert_eq!(e.to_string(), "I/O error [chunk 7]");
}
#[test]
fn is_not_found_matches_codes() {
assert!(service("GetObject", Some("NoSuchKey"), None, None).is_not_found());
assert!(!service("GetObject", Some("AccessDenied"), None, None).is_not_found());
}
#[test]
fn display_child_operation_failed_bare() {
let e = Error::new(ErrorKind::ChildOperationFailed, "x");
assert_eq!(e.to_string(), "child operation failed");
}
#[test]
fn display_child_operation_failed_names_first_and_count() {
let failed = vec![
FailedUpload {
input: None,
error: Error::new(ErrorKind::ServiceError, "boom"),
source_path: Some(std::path::PathBuf::from("/data/a.bin")),
},
FailedUpload {
input: None,
error: Error::new(ErrorKind::ServiceError, "boom"),
source_path: Some(std::path::PathBuf::from("/data/b.bin")),
},
];
let e = Error::new(ErrorKind::ChildOperationFailed, "aborted").with_failed_uploads(failed);
assert_eq!(
e.to_string(),
"child operation failed: /data/a.bin (and 1 more)"
);
}
#[test]
fn display_child_operation_failed_single_no_path() {
let failed = vec![FailedUpload {
input: None,
error: Error::new(ErrorKind::ServiceError, "boom"),
source_path: None,
}];
let e = Error::new(ErrorKind::ChildOperationFailed, "aborted").with_failed_uploads(failed);
assert_eq!(e.to_string(), "child operation failed: 1 object");
}
#[test]
fn display_local_context_names_action_and_path() {
let e = io_at(
"creating temporary file for",
"out/logs/a.log",
std::io::Error::from(std::io::ErrorKind::NotFound),
);
assert_eq!(
e.to_string(),
"I/O error creating temporary file for \"out/logs/a.log\""
);
let source = std::error::Error::source(&e)
.and_then(|s| s.downcast_ref::<std::io::Error>())
.expect("the io::Error is the direct source");
assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
let e = io_at(
"creating directory",
"out/logs",
std::io::Error::from(std::io::ErrorKind::PermissionDenied),
)
.with_local_key("logs/a.log");
assert_eq!(
e.to_string(),
"I/O error creating directory \"out/logs\" (key \"logs/a.log\")"
);
let e = Error::new(ErrorKind::IOError, "x").with_local_key("logs/a.log");
assert_eq!(e.to_string(), "I/O error");
}
#[test]
fn display_walker_error_names_path() {
use crate::io::walk::{WalkError, WalkErrorKind};
let e = Error::from(WalkError::new(
Some(std::path::PathBuf::from("/data/sub")),
WalkErrorKind::PermissionDenied,
Box::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
));
assert_eq!(e.kind(), &ErrorKind::IOError);
assert_eq!(e.to_string(), "I/O error walking \"/data/sub\"");
let root = Error::from(WalkError::new(
Some(std::path::PathBuf::from("/data/missing")),
WalkErrorKind::SourceUnreadable,
Box::new(std::io::Error::from(std::io::ErrorKind::NotFound)),
));
assert_eq!(root.kind(), &ErrorKind::InputInvalid);
assert_eq!(root.to_string(), "invalid input walking \"/data/missing\"");
}
#[test]
fn child_operation_failed_source_is_first_failed_child() {
let failed = vec![
FailedUpload {
input: None,
error: Error::new(ErrorKind::ServiceError, "first"),
source_path: None,
},
FailedUpload {
input: None,
error: Error::new(ErrorKind::ServiceError, "second"),
source_path: None,
},
];
let e = Error::new(ErrorKind::ChildOperationFailed, "aborted").with_failed_uploads(failed);
let source = std::error::Error::source(&e)
.and_then(|s| s.downcast_ref::<Error>())
.expect("the source is a child's error");
assert!(std::ptr::eq(source, e.failed_uploads().unwrap()[0].error()));
let bare = Error::new(ErrorKind::ChildOperationFailed, "aborted");
assert_eq!(
std::error::Error::source(&bare).map(|s| s.to_string()),
Some("aborted".to_owned())
);
}
#[test]
fn upload_id_is_none_unless_attached() {
let e = Error::new(ErrorKind::ServiceError, "x");
assert_eq!(e.upload_id(), None);
let e = e.with_upload_id("abc".to_owned());
assert_eq!(e.upload_id(), Some("abc"));
assert_eq!(e.to_string(), "service error");
}
use aws_sdk_s3::operation::get_object::GetObjectError;
fn dispatch(conn: ConnectorError) -> SdkError<GetObjectError, HttpResponse> {
SdkError::dispatch_failure(conn)
}
#[test]
fn transient_nested_transient_marker_under_other_none_is_transient() {
let inner = ConnectorError::other(
"incomplete message".into(),
Some(RetryErrorKind::TransientError),
);
let inner_sdk: SdkError<GetObjectError, HttpResponse> = SdkError::dispatch_failure(inner);
let outer = ConnectorError::other(Box::new(inner_sdk), None);
assert!(
is_sdk_transient_transport(&dispatch(outer)),
"a TransientError marker nested under an outer Other(None) must classify transient"
);
}
#[test]
fn transient_outer_io_is_transient() {
assert!(is_sdk_transient_transport(&dispatch(ConnectorError::io(
"reset".into()
))));
}
#[test]
fn transient_outer_timeout_is_transient() {
assert!(is_sdk_transient_transport(&dispatch(
ConnectorError::timeout("connect".into())
)));
}
#[test]
fn transient_bare_other_none_is_not_transient() {
assert!(!is_sdk_transient_transport(&dispatch(
ConnectorError::other("unclassified".into(), None)
)));
}
#[test]
fn transient_user_error_is_not_transient() {
assert!(!is_sdk_transient_transport(&dispatch(
ConnectorError::user("bad request".into())
)));
}
use aws_smithy_runtime_api::http::StatusCode;
use aws_smithy_types::body::SdkBody;
#[test]
fn precondition_failure_surfaces_as_service_error_with_code() {
let sdk: SdkError<PutObjectError, HttpResponse> = SdkError::service_error(
PutObjectError::generic(
aws_smithy_types::error::ErrorMetadata::builder()
.code("PreconditionFailed")
.build(),
),
HttpResponse::new(StatusCode::try_from(412).unwrap(), SdkBody::empty()),
);
let err = service_error(sdk);
assert!(matches!(err.kind(), ErrorKind::ServiceError));
assert_eq!(err.code(), Some("PreconditionFailed"));
assert_eq!(err.operation_name(), Some("PutObject"));
assert!(std::error::Error::source(&err)
.and_then(|s| s.downcast_ref::<SdkError<PutObjectError, HttpResponse>>())
.is_some());
}
}