rustaws-sdk-rust

Error matching with downcasting the struct error types in AWS SDK


I have this code in Go:

_, err := kms.ScheduleKeyDeletion(...
ev, ok := err.(awserr.Error)
deleted := false
if ok {
    switch ev.Code() {
        case "KMSInvalidStateException":
            deleted = strings.Contains(aerr.Message(), "pending deletion")
        case "NotFoundException":
            deleted = true
    }
}

Basically, want to do the same in Rust using https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.schedule_key_deletion

let result = cli.schedule_key_deletion().send().await;
let success = match result {
  Ok(ok_result) => { ... },
  Err(e) => {
    // "e" is the 'aws_sdk_kms::error::ScheduleKeyDeletionError' type
    // ref. https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/error/struct.ScheduleKeyDeletionError.html
    match e {
      // doesn't compile...
      aws_sdk_kms::error::NotFoundException => {
        true
      },
      _ => false
    }
  }
}

Basically, on the return type https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/error/struct.ScheduleKeyDeletionError.html, I want to check if the return struct is https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/error/struct.NotFoundException.html or not.

#[non_exhaustive]
pub struct ScheduleKeyDeletionError {
    pub kind: ScheduleKeyDeletionErrorKind,
    /* private fields */
}
#[non_exhaustive]
pub struct NotFoundException {
    pub message: Option<String>,
}

Solution

  • You can use e.kind() to get the Kind of error that occurred. The return value of e.kind will be of Enum type ScheduleKeyDeletionErrorKind. So you can match the enum variant aws_sdk_kms::error::ScheduleKeyDeletionErrorKind::NotFoundException to see if there an NotFoundException Exception.

    let result = cli.schedule_key_deletion().send().await;
    let success = match result {
      Ok(ok_result) => { ... },
      Err(e) => {
        match e.kind() {
          aws_sdk_kms::error::ScheduleKeyDeletionErrorKind::NotFoundException(_)=> {
            true
          },
          _ => false
        }
      }
    }
    

    Note: This solution is not tested.